C# 存取SqlServer中的Image型別

iDotNetSpace發表於2009-03-10

有時候我們需要將圖片存到數庫中的Imgae型別的欄位下,以下是存取的兩種方法:

存:

public void Save()

{

using(System.IO.FileStream stream = new System.IO.FileStreamfile,System.IO.FileMode.Open,System.IO.FileAccess.Read)

{
    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();

}

}

取:

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;

}

}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-566606/,如需轉載,請註明出處,否則將追究法律責任。

相關文章