我想使用c#winforms和dapper micro orm在SqlServer中保存Image。
db中的 Photo
字段的类型为VARBINARY(MAX)
Inside Book实体我有类型为byte []的Photo属性。
public Book
{
...
public byte[] Photo { get; set; }
}
内部winforms窗口我有
OpenFileDialog open = new OpenFileDialog() { Filter = "Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.png;*.jpg" };
if (open.ShowDialog() == DialogResult.OK)
{
txtPhoto.Text = open.FileName;
}
string image = txtPhoto.Text;
Bitmap bmp = new Bitmap(image);
FileStream fs = new FileStream(image, FileMode.Open, FileAccess.Read);
byte[] bimage = new byte[fs.Length];
fs.Read(bimage, 0, Convert.ToInt32(fs.Length));
fs.Close();
byte[] Photo = bimage;
//在我的存储库中我在第Photo = @Photo
行保存对象时出错
var sql = "UPDATE Book " +
"SET Title = @Title, " +
" Language = @Language, " +
....
" Photo = @Photo" +
"WHERE Id = @Id";
this.db.Execute(sql, book); // error occures
return book;
错误是
类型'System.Data.SqlClient.SqlException'的第一次机会异常 发生在System.Data.dll
中其他信息:“照片”附近的语法不正确。
我错过了什么吗?
由于
答案 0 :(得分:1)
WHERE
关键字之前缺少空格:
" Photo = @Photo" + // no space at the end here
"WHERE Id = @Id"; // and no space before WHERE here
另外,我建议你对sql查询文本使用多行字符串(即verbatim string literal)(使查询更具可读性):
var sql = @"UPDATE Book
SET Title = @Title,
Language = @Language,
Photo = @Photo
WHERE Id = @Id";
还有一件事 - 最好将Stream
用法包装到using
块中(以便在发生异常时释放文件句柄):
byte[] photo;
using(var stream = File.OpenRead(txtPhoto.Text)
{
photo = new byte[stream.Length];
stream.Read(photo, 0, photo.Length);
}
// db query with dapper is OK