• SQLserver中存储图片


    两种方式
    1、存放图片路径
    2、转换成2进制流(不过这样的话将很占用数据库空间)
    存路径的方式就很简单了,下面着重给出转换成2进制流的存入以及读取方法。
    存入:
    string FilePath="";
    OpenFileDialog oFileDialog=new OpenFileDialog();
    if(oFileDialog.ShowDialog()==DialogResult.OK)
    {
    FilePath=oFileDialog.FileName;
    FileStream fs=new FileStream(FilePath,FileMode.Open,FileAccess.Read);
    byte[] bytes=new byte[fs.Length];
    string sql = "insert PicSave(FileName,FileType,FileData)values(@FN,@FT,@MF)";
    SqlCommand com = new SqlCommand(sql,this.sqlCon);
    SqlParameter FN = new SqlParameter("@FN",SqlDbType.VarChar);
    FN.Value = "泳装妹妹";
    com.Parameters.Add(FN);
    SqlParameter FT = new SqlParameter("@FT",SqlDbType.VarChar);
    FT.Value = "JPG";
    com.Parameters.Add(FT);
    SqlParameter MF = new SqlParameter("@MF",SqlDbType.Image);
    MF.Value = bytes;
    com.Parameters.Add(MF);
    com.CommandType = CommandType.Text;

    sqlCon.ConnectionString = this.conStr;

    try
    {
    sqlCon.Open();
    com.ExecuteNonQuery();
    sqlCon.Close();
    MessageBox.Show("存入成功!");
    }
    catch(Exception ex)
    {
    throw ex;
    }
    finally
    {
    sqlCon.Close();
    }

    }
    读出:
    int id=Convert.ToInt32(this.textBox1.Text.Trim());
    string sql = "select FileData from PicSave where id ="+id+" ";

    sqlCon.ConnectionString = this.conStr;

    SqlCommand readComm = new SqlCommand(sql,this.sqlCon);

    SqlDataReader dr = null;

    FileStream fs = null;

    BinaryWriter bw = null;

    int bufferSize = 100;

    byte[] outbyte = new byte[bufferSize];

    long retval;

    long startIndex = 0;

    try
    {
    sqlCon.Open();
    dr = readComm.ExecuteReader();
    while(dr.Read())
    {
    fs = new FileStream("TakeOut.jpg",FileMode.OpenOrCreate,FileAccess.Write);

    bw = new BinaryWriter(fs);

    retval = dr.GetBytes(0, startIndex, outbyte, 0, bufferSize);

    while (retval == bufferSize)
    {
    bw.Write(outbyte);
    bw.Flush();

    startIndex += bufferSize;
    retval = dr.GetBytes(0, startIndex, outbyte, 0, bufferSize);
    }
    bw.Write(outbyte, 0, (int)retval - 1);
    bw.Flush();
    bw.Close();
    fs.Close();
    Image im = Image.FromFile("TakeOut.jpg");

    this.pictureBox1.Image = im;
    }
    sqlCon.Close();
    }
    catch(Exception ex)
    {
    throw ex;
    }
    finally
    {
    sqlCon.Close();
    bw.Close();
    fs.Close();
    }

  • 相关阅读:
    H3C交换机删除VLAN与其绑定端口配置
    H3CNE实验:配置交换机接口
    在H3C交换机上开通一个VLAN并且开通一个端口ping通它
    局域网交换技术知识点
    Java开发中常用的设计模式(二)---单例模式
    Java开发中常用的设计模式(一)---工厂模式
    DevExpress13.2.9 控件使用经验总结
    基于.Net下整合RestSharp,实现REST服务客户端
    基于.Net下整合FastReport,实现条码标签批量打印
    基于.Net下整合IBatis
  • 原文地址:https://www.cnblogs.com/ZGQ-VIP/p/11800413.html
Copyright © 2020-2023  润新知