向数据库中插入图片
很长时间都没有做程序了,今天心血来潮做了一个,却错误百出.没有办法的情况下,只好求助于大家了.1.添加命名空间
using System.Data.SqlClient;
using System.IO;
using System.Drawing.Imaging;
2.设置局部变量
private string constr = "integrated security=SSPI;data source=MICROSOF-B1978E;initial catalog=xuexi";//constr为数据库连接字符串
private string sqlstr;//sql字符串
private byte[] b;
3.具体实现
private void button1_Click(object sender, System.EventArgs e)
{
openFileDialog1=new OpenFileDialog();
openFileDialog1.ShowDialog();
// pictureBox1.Image=Image.FileFrom(openFileDialog1.FileName);
//这个是从网上找的,本来有这句话,添加上说并不包含对“FileFrom”的定义 问题所在
//不要的情况下也可以运行,但就是出现"对象必须实现IConvertible"的错误.
FileStream fs=new FileStream(openFileDialog1.FileName,FileMode.Open,FileAccess.Read);
b=new byte[fs.Length];
fs.Read(b,0,b.Length);
SqlConnection conn=new SqlConnection(constr);
conn.Open();
sqlstr=@"insert into Image values(@Id,@title,@type,@photo)";
SqlCommand comm=new SqlCommand(sqlstr,conn);
comm.Parameters.Add("@Id",SqlDbType.Int,4,"ImgID");
comm.Parameters.Add("@title",SqlDbType.NVarChar,50,"ImgTitle");
comm.Parameters.Add("@type",SqlDbType.NVarChar,50,"ImgType");
comm.Parameters.Add("@photo",SqlDbType.Image,16,"ImgData");
comm.Parameters["@Id"].Value=b;
comm.Parameters["@title"].Value=b;
comm.Parameters["@type"].Value=b;
comm.Parameters["@photo"].Value=b;
try
{
comm.ExecuteNonQuery();
}
catch(Exception err)
{
MessageBox.Show(err.Message);
}
conn.Close();
}