How to insert PictureBox to Sql Server Database Varbinary(MAX) with C#?

故事扮演 提交于 2021-02-16 20:18:01

问题


I have a table that have a field as Varbinary(MAX) datatype and I want to insert image file from PictureBox into this column. So how can I convert and insert image to Varbinary in Sql Server. Thank for help me.


回答1:


You should really show some code, what have you tried...

This is only a guess, but it should give you a clue how to insert picture into database:

//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();


来源:https://stackoverflow.com/questions/43323124/how-to-insert-picturebox-to-sql-server-database-varbinarymax-with-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!