将图像保存到SQL Server数据库中

时间:2017-10-16 11:03:53

标签: c# sql-server

当我将图像插入SQL Server数据库时,如果图像为null,则它会将0x值插入数据库图像列。

当我使用0x十六进制值检索图像时,出现错误:

  

参数无效

string strsql = "SELECT [ID],PIC_Name FROM [HRMS].[dbo].[Employee_PC] where Id = '" + mFieldValue1 + "'";   
myconn = new OleDbConnection(clsConnections.conString);
myconn.Open();

cmd = new OleDbCommand(strsql, myconn);
OleDbDataReader dr = null;

dr = cmd.ExecuteReader();
while (dr.Read())
{
    if ((byte[])dr[1]  == null )
    //if (picData == null) 
    {
      pictureBox1.Image = null;
    }
    else
    {
      MemoryStream ms = new MemoryStream((byte[])dr[1]);
      ms.Position = 0;
      pictureBox1.Image = new Bitmap(ms);
    }
}

1 个答案:

答案 0 :(得分:0)

dr[1]不会null,因此(byte[])dr[1]也不会。您想检查该数组中的第一个字节

byte[] picData = (byte[])dr[1];

if (picData[0] == 0)
{
  pictureBox1.Image = null;
}
else
{
  MemoryStream ms = new MemoryStream(picData);
  ms.Position = 0;
  pictureBox1.Image = new Bitmap(ms);
}