C#基础——winform应用上传图片到SQLServer数据库

前言

之前通过winform与SQL Server的交互一直局限于文本、数字等信息,都可以通过string的方式来传输,但是比如音乐、图片等特殊格式的文件要如何与SQL Server数据库进行交互呢?

今天主要讲通过文件流的方式,将特殊文件转换成二进制,然后存储到数据库中。在实际的应用中,如果文件较大或者较多,直接存储在数据中会造成一定的压力,可以转为保存文件名,然后在实际使用的地方调用改文件名对应的文件。

主要内容

C#基础——winform应用上传图片到SQLServer数据库

上图为图片上传winform的内容。

1、选择图片按钮,功能为通过对话框选择要上传的文件,并将该文件在下面的pictureBox中显示出来。具体代码如下:

 private void btn_Choose_Click(object sender, EventArgs e)
{
UserMethod.ShowPic(this.pictureBox1);
}
  public static void ShowPic(PictureBox picBox)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = @"E:\";
ofd.Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files(*.*)|*.*";
ofd.RestoreDirectory = true; if (ofd.ShowDialog() == DialogResult.OK)
{
picAddress = ofd.FileName;
Image imge = Image.FromFile(picAddress);
Bitmap bm = new Bitmap(imge, picBox.Width, picBox.Height);
picBox.Image = bm;
}
}

ShowPic()方法为静态方法,可以直接调用,其中的picAddress变量为静态全局变量,用于记录要上传文件的文件地址。picturebox显示图片的方式,是通过pictbox的image属性设定的,将图片转成Bitmap格式,位图文件是最简单的图片格式。

2、上传图片,该按钮的功能是将选定的图片上传到数据库中,具体的实现代码如下:

  private void btn_Upload_Click(object sender, EventArgs e)
{
if (UserMethod.picAddress == null)
{
Byte[] pic = UserMethod.GetContent(UserMethod.picAddress);
string sql = "insert into tb_MyPic values(@Picture,@PicCategory)";
SqlParameter[] param = new SqlParameter[];
param[] = new SqlParameter("@Picture", pic);
param[] = new SqlParameter("@PicCategory", this.cmbCatogery.Text.Trim());
if (DataBase.getExecuteQuery(sql, param) != )
{
MessageBox.Show("添加成功!");
}
}
else
{
MessageBox.Show("请先选择图片!");
}
}
      public static string picAddress = string.Empty;
public static Byte[] GetContent(string filepath)//将指定路径下的文件转换成二进制代码,用于传输到数据库
{
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
Byte[] byData = new Byte[fs.Length];//新建用于保存文件流的字节数组
fs.Read(byData, , byData.Length);//读取文件流
fs.Close();
return byData;
}

上传的过程大概就是:根据文件地址将对应文件转换成数据流二进制格式-->编写对应的SQL语句-->执行该SQL语句,将图片添加到数据库中。

3、使用sql Parameter[]的SQL执行方法,因为传统的sql语句对应的value终归是string或者int之类的格式,可以在sql语句中写一下,但是使用Parameter的方式可以更加简洁、明了、减少失误。具体的执行sql语句方法参考如下代码:

  public static int getExecuteQuery(string sql, SqlParameter[] param)
{
getcon();
SqlCommand sqlcom = new SqlCommand(sql, My_Conn);
sqlcom.Parameters.AddRange(param);
return sqlcom.ExecuteNonQuery();
}

OK,下次会跟大家讲一下如何从sql数据中下载图片显示到winform中来。

上一篇:firefox怎么修改tls协议号


下一篇:Liunx下的有关于tomcat的相关操作 && Liunx 常用指令