如何使用C#将PictureBox插入到Sql Server Database Varbinary(MAX)?

时间:2017-04-10 12:26:09

标签: c# sql-server stored-procedures

我有一个表,其字段为Varbinary(MAX)数据类型,我想将PictureBox中的图像文件插入此列。那么如何在Sql Server中将图像转换并插入到Varbinary中。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

你应该真的展示一些代码,你尝试过什么......

这只是猜测,但它应该为您提供如何将图片插入数据库的线索:

//byte array that will hold image data
byte[] imageData = null;

using (var ms = new MemoryStream())
{
    //here is image property of your pictureBox control  saved into memory stream
    pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
    imageData = ms.ToArray();
}

//make sql connection
SqlConnection conn = new SqlConnection("your connection string goes here");
// command with parameter
SqlCommand cmd = new SqlCommand("insert into TableWithImages (imageData) values (@imageData);", conn);
//define param and pass byte array as value
cmd.Parameters.Add("@imageData", SqlDbType.VarBinary).Value = imageData;

//do insert
cmd.ExecuteNonQuery();