byte[] FileByteArray;
System.IO.MemoryStream ImageStream;
this.sqlConnection1.ConnectionString=strConn;
try
{
if(this.sqlConnection1.State==ConnectionState.Closed)
this.sqlConnection1.Open();
this.sqlCommand1.CommandText="insert into MyImage ( MyImage ) values ( @MyImage )";
ImageStream=new MemoryStream();
image1.Save(ImageStream,System.Drawing.Imaging.ImageFormat.Jpeg);
FileByteArray=new byte[Convert.ToInt32(ImageStream.Length)];
ImageStream.Read(FileByteArray,0,Convert.ToInt32(ImageStream.Length));
sqlCommand1.Parameters.Add(new SqlParameter("@MyImage",SqlDbType.Image,Convert.ToInt32( ImageStream.Length))).Value = FileByteArray;
sqlCommand1.ExecuteNonQuery();
MessageBox.Show("添加成功!");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

该博客展示了使用C#将图片数据插入数据库的代码。通过创建内存流存储图片,将图片转换为字节数组,再使用SQL命令将字节数组插入数据库。代码中包含异常处理,若插入成功会提示“添加成功!”,若出现异常则显示异常信息。
4285

被折叠的 条评论
为什么被折叠?



