C#winform图片存入数据库问题
byte[] imgBytesIn;
//添加
private void button1_Click(object sender, EventArgs e)
{
if (this.openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
try
{
this.pictureBox1.Image = Image.FromStream(this.openFileDialog1.OpenFile());
string strimg = openFileDialog1.FileName.ToString();
FileStream fs = new FileStream(strimg, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
imgBytesIn = br.ReadBytes((int)fs.Length);
}
catch
{
MessageBox.Show("您选择的图片不能被读取或文件类型不对!","错误",MessageBoxButtons.OK,MessageBoxIcon.Warning);
this.pictureBox1.Image = null;
}
}
}
//保存到数据库
private void button2_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("server=.;database=FilesDB;uid=sa;pwd=sa");
conn.Open();
string sql =string.Format("insert into imagestore values '{0}'",imgBytesIn);
SqlCommand comm = new SqlCommand(sql,conn);
comm.Parameters.Add("imagevalue",SqlDbType.Image).Value = imgBytesIn;
try
{
if (comm.ExecuteNonQuery() == 1)
{
MessageBox.Show("保存成功");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
conn.Close();
}
红色字体部分报出错误:'System.Byte[]' 附近有语法错误!
------解决方案--------------------string sql =string.Format("insert into imagestore values '{0}'",imgBytesIn);
imgBytesIn是byte[]类型,怎么能和sql频道一起呢,用参数赋值
http://www.cnblogs.com/tuyile006/archive/2007/01/08/614718.html
------解决方案--------------------
SqlConnection conn = new SqlConnection("server=.;database=FilesDB;uid=sa;pwd=sa");
conn.Open();
string sql = string.Format("insert into imagestore values (@imagevalue)");
SqlCommand comm = new SqlCommand(sql, conn);
comm.Parameters.Add("@imagevalue", SqlDbType.Image).Value = imgBytesIn;
------解决方案-------------------- sql = "Insert into Person(Photo) values(@Image)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@Image", SqlDbType.VarBinary);
cmd.Parameters["@Image"].Value = picbyte;
cmd.ExecuteNonQuery();
或
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@Image", SqlDbType.Image).Value = picbyte;