如何将图片存入数据库
如何将图片存入数据库:将图片存入数据库,首先要在数据库中建立一张表,将存储图
片的字段类型设为 Image 类型,用 FileStream 类、BinaryReader 把图片读成字节的形式,赋
给一个字节数组,然后用 ADO.SqlCommand 对象的 ExecuteNonQuery()方法来把数据保存到
数据库中。参考代码如下:
private void button1_Clickobject sender, EventArgs e)
{
openFileDialog1.Filter = "*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP";
if(openFileDialog1.ShowDialog()==DialogResult.OK)
{
string fullpath =openFileDialog1.FileName;//文件路径
FileStream fs = new FileStream(fullpath, FileMode.Open);
byte[] imagebytes =new byte[fs.Length];
BinaryReader br = new BinaryReader(fs);
imagebytes = br.ReadBytes(Convert.ToInt32(fs.Length));
SqlConnection con=new SqlConnection("server=(local); uid=sa; pwd=;
database=db_05");
con.Open();
SqlCommand com = new SqlCommand("insert into tb_08 values(@ImageList)",
con);
com.Parameters.Add("ImageList", SqlDbType.Image);
com.Parameters["ImageList"].Value = imagebytes;
com.ExecuteNonQuery();
con.Close();
}
}
评论0
最新资源