如何存储图像空值

问题描述 投票:-1回答:1

当图片框中没有可用的图像时,我想存储空值。但我试过但不能这样做。任何身体都可以;

byte[] img = null;

FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);

cmd = new SqlCommand("insert into [" + timpickervalue + "]([serialno],@img)",con);
cmd.Parameters.Add("@img", img);
c# sql
1个回答
0
投票

像这样的东西:

//DONE: Often, it's easier to use File class then Stream's
// If imgLoc provided, let's load img from file; otherwise assign null
byte[] img = !string.IsNullOrWhiteSpace(imgLoc) 
  ? File.ReadAllBytes(imgLoc)
  : null;

...

//DONE: string interpolation / formtting makes SQL more readable
string sql = 
  $@"insert into [{timpickervalue}] 
          values ([serialno], 
                  @img)";

//DONE: wrap IDisposable into using
using (SqlCommand cmd = new SqlCommand(sql, con)) { 
  //DONE: create and assign the parameter 
  //TODO: Put the right condition when Null should be assigned (I suggested null or empty)
  if (img == null || img.Length <= 0)
    cmd.Parameters.Add("@img", SqlDbType.Image, 0).Value = DBNull.Value;    
  else
    cmd.Parameters.Add("@img", SqlDbType.Image, img.Length).Value = img;

  //DONE: do not forget to run the query
  cmd.ExecuteNonQuery(); 
}
© www.soinside.com 2019 - 2024. All rights reserved.