ADO.net存取image类型

最近试验需求,用到了sql server中的image字段,存取方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void Save()
{
using (System.IO.FileStream stream = new System.IO.FileStream())
{
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, (int)stream.Length);
stream.Close();
string strName = System.IO.Path.GetFileNameWithoutExtension(file);
SqlCommand cmd = new SqlCommand("Insert into Temp(name,photo) values(@name,@image)", sqlConn);
cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = strName;
cmd.Parameters.Add("@image", SqlDbType.Image).Value = buffer;
cmd.ExecuteNonQuery();
}
}

取:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void GetImage()
{
SqlCommand cmd = new SqlCommand(@"SELECT name, photo FROM Temp", sqlConn);
sqlConn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
image_filename = (string)reader.GetValue(0);
byte[] image_bytes = (byte[])reader.GetValue(1);
MemoryStream ms = new MemoryStream(image_bytes);
Bitmap bmap = new Bitmap(ms);
return bmap;

}
}
作者

Wu Rang

发布于

2010-12-10

更新于

2024-06-13

许可协议

评论