[英]Saving image in sql database C#
当用户选择图像时,我想将图像保存在SQL数据库中。 到目前为止,我已经输入了此代码。 这不会给我任何错误,但不会添加到数据库中。 我认为SQL语句出了点问题。
有人能帮我吗?
这是我的代码:
public void addImages(string tag1,string tag2,string tag3,string status,string fileName)
{
try
{
byte[] image = null;
FileStream fsstream = new FileStream(fileName,FileMode.Open,FileAccess.Read);
BinaryReader br = new BinaryReader(fsstream);
image = br.ReadBytes((int)fsstream.Length);
SqlCommand command = new SqlCommand("INSERT INTO [ImagesAndTags] (Images,Tags,Tag2,Tag3,Status) values (@IMG,'" + tag1 + "','" + tag2 + "','" + tag3 + "','" + status + "')", con);
con.Open();
command.Parameters.Add(new SqlParameter("@IMG",image));
SqlDataReader reader = command.ExecuteReader();
MessageBox.Show("Added Successfully!!!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
while (reader.Read()) { }
}
catch(Exception ex) { }
}
ExecuteReader
返回数据。 就您而言,事实并非如此。 您只需尝试在数据库中插入一行。 这就是为什么您需要改用ExecuteNonQuery
的原因。
并像对image
变量一样参数化其他插入值。 还可以使用using
语句来处理数据库连接和命令。
int insertedRowCount = command.ExecuteNonQuery();
if(insertedRowCount > 0)
MessageBox.Show("Added Successfully!!!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
从您存储在数据库中的数据中删除所有反斜杠,单反逗号和双反逗号。
将其替换为一些常量字符串,然后再次取回它,将其转换为原始字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.