简体   繁体   中英

Saving Image into SQL Server database

When I insert an image into a SQL Server database, if the image is null, then it inserts a 0x value into the database image column.

When I retrieve the image with 0x hex value, I get an error:

Parameter is not valid

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

dr[1] won't be null , so neither will (byte[])dr[1] . You want to check the first byte in that array.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM