C# 在SQLSERVER数据库中存取图片

时间:2022-04-30 04:45:48

 

//放入数据库
if(this.openFileDialog1.ShowDialog()==DialogResult.OK)
{
this.pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
SqlConnection conn 
= new SqlConnection("server=(local);uid=sa;pwd=sa;database=ac");
conn.Open();
SqlCommand cmd 
= new SqlCommand("insert into xia (names) values (@i)", conn);
byte[] ib = new Byte[6000000];
FileStream fs 
= new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
fs.Read(ib, 
06000000);
cmd.Parameters.Add(
"@i", SqlDbType.Image, (int)fs.Length);
cmd.Parameters[
"@i"].Value = ib; cmd.ExecuteNonQuery();
conn.Close();
}

//从数据库中读取
try
{
System.Data.SqlClient.SqlConnection conn 
= new SqlConnection(connstring);
conn.Open();
string sql = "select ImageNum from image where ImageName=@name";
SqlCommand comm 
= new SqlCommand(sql, conn);
string strname = listBox1.SelectedItem.ToString();
comm.Parameters.Add(
"@name", SqlDbType.NVarChar).Value = strname;
System.Data.SqlClient.SqlDataAdapter adapter 
= new SqlDataAdapter();
adapter.SelectCommand 
= comm;
System.Data.DataSet dataset 
= new DataSet();

adapter.SelectCommand.ExecuteNonQuery();
adapter.Fill(dataset, 
"image");
byte[] b = (byte[])dataset.Tables[0].Rows[0]["ImageNum"];
if (b.Length > 0)
{
MemoryStream stream 
= new MemoryStream(b, true);
stream.Write(b, 
0, b.Length);
System.Drawing.Bitmap bitmap 
= new Bitmap(stream);
imageshow.Image 
= bitmap;

imageshow.Left 
= 700;
imageshow.Width 
= 300;
imageshow.Height 
= 300;
stream.Close();
}
conn.Close();
}
catch (Exception)
{
MessageBox.Show(
"你可能没选择图片,请选择");
}