AddingImagetoSQLDatabaseUsingVisualC#我正在开发一个用于图像处理的可视化C#程序。我正在尝试使用VisualC#(Windows窗体)和ADO.NET将图像添加到sql数据库。我已经使用文件流方法将图像转换为二进制形式,但是图像字节没有保存在数据库中。在数据库图像栏中显示,没有保存任何数据!我已经尝试了很多插入方法(有和没有存储过程等),但总是在数据库中得到相同的东西。privatevoidbutton6_Click(objectsender,EventArgse){try{byte[]image=null;pictureBox2.ImageLocation=textBox1.Text;字符串文件路径=textBox1.Text;FileStreamfs=newFileStream(文件路径,FileMode.Open,FileAccess.Read);BinaryReaderbr=newBinaryReader(fs);image=br.ReadBytes((int)fs.Length);stringsql="INSERTINTOImageTable(Image)VALUES(@Imgg)";if(con.State!=ConnectionState.Open)con.Open();SqlCommandcmd=newSqlCommand(sql,con);cmd.Parameters.Add(newSqlParameter("@Imgg",image));intx=cmd.ExecuteNonQuery();con.Close();MessageBox.Show(x.ToString()+"图片已保存");我没有在代码中收到错误。图像被转换,输入在数据库中完成,但显示在sql数据库中。所选文件流应转换为字节数组。FileStreamFS=newFileStream(文件路径,FileMode.Open,FileAccess.Read);//创建一个文件流对象关联到用户选择的文件byte[]img=newbyte[FS.Length];//创建一个字节数组,其大小为用户选择的文件流长度FS.Read(img,0,Convert.ToInt32(FS.Length));//将用户选择的文件流读入字节数组现在这很好用。数据库仍然显示,但可以使用memorystream方法将其转换回图像。谢谢大家...尝试这样的事情:byte[]fileBytes=System.IO.File.ReadAllBytes("pathtofile");System.Data.SqlClient.SqlCommandcommand=newSystem.Data.SqlClient.SqlCommand("insertintotable(blob,filename)values(@blob,@name)");命令.Parameters.AddWithValue("blob",fileBytes);command.Parameters.AddWithValue("名称","文件名");命令.ExecuteNonQuery();假设您正在使用VARBINARY来存储图像(您应该这样做),您可能需要使SqlParameter更加类型化:而不是cmd.Parameters.Add(newSqlParameter("@Imgg",image));你会使用:cmd。Parameters.Add("@Imgg",SqlDbType.VarBinary).Value=(SqlBinary)image;您还可以使用System.IO.File.ReadAllBytes来缩短将文件路径转换为字节数组的代码。执行这个存储过程:createprocedureprcInsert(@txtEmpNovarchar(6),@photoimage)asbegininsertintoEmpvalues(@txtEmpNo,@photo)endtableEmp:以上是C#学习教程:用VisualC#添加imagesSQL数据库上分享的所有内容,如果对你有用,需要了解更多C#学习教程,希望大家多多关注——createtableEmp([txtEmpNo][varchar](6)NOTNULL,imPhoto图片)本文来自网络收藏不代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
