两种方式
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();
}