我想在图片框中没有可用的图像时存储空值。 但我试过但不能这样做。 任何身体都可以发挥;
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);
答案 0 :(得分: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();
}