winform 中如何将图片以二进制存到数据库中

来源:百度知道 编辑:UC知道 时间:2024/05/17 07:17:07

将图片转成BYTE字节数组

一般存的是路径

数据库中建立一个字段是二进制类型的,另外建立一个字段是文本类型的,在C#中使用带有参数的SQL来添加数据到数据库,当然你需要将声音文件先读入到内存转换为二进制赋值给sql的参数即可。

首先..定义一个函数..将图片转化为二进制码
//定义将图片转化为长二进制代码的函数getphoto()
public Byte[] getphoto(string photopath)
{
string str = photopath;
FileStream file = new FileStream(str, FileMode.Open, FileAccess.Read);
Byte[] bytBLOBData = new Byte[file.Length];
file.Read(bytBLOBData, 0, bytBLOBData.Length);
file.Close();
return bytBLOBData;
}//这是定义函数..

然后..就是将转换成二进制码的图片插入数据库中..下面是简单的也是重要的sql语句..
if (this.pictureBox1.Image != null)
{
sql1 = sql1 + ",Photo";
sql2 = sql2 + ",bytBLOBData";
Byte[] bytBLOBData = getphoto(openFileDialog1.FileName);
cmd.Parameters.Add(new OleDbParameter("jpeg", OleDbType.Binary, bytBLOBData.Length, ParameterDirection.Input, true, 0, 0, null, DataRowVersion.Default, bytBLOBData));
}

接下来..是读取...

string sql = &q