• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
子目枫林
博客园    首页    新随笔    联系   管理    订阅  订阅

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

posted @ 2019-11-05 18:26  子目枫林  阅读(3214)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3