您的位置:首页 > 数据库

将图片以二进制形式存入数据库中

2010-06-17 18:10 253 查看
将图片以二进制形式存入数据库时,首先要在数据库中建立一张表,将存储图片的字段类型设为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();
}
}
                ——摘自《C#编程词典》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: