[英]Insert image to local SQL Server database in ASP.NET
I want to add image from FileUpload
to a local SQL Server database in ASP.NET. 我想将图像从
FileUpload
添加到ASP.NET中的本地SQL Server数据库。
I have read many same questions, but they didn't help me:( 我读过很多相同的问题,但是它们并没有帮助我:(
int length = FileUpload.PostedFile.ContentLength;
byte[] picSize = new byte[length];
HttpPostedFile uplImage= FileUpload.PostedFile;
uplImage.InputStream.Read(picSize, 0, length);
SqlCommand com = new SqlCommand("INSERT INTO [Table] (Name, Picture) values (@Name, @Picture)", con);
com.Parameters.AddWithValue("@Name", TextName.Text);
com.Parameters.AddWithValue("@Picture", picSize);
com.ExecuteNonQuery();
So if I simply add column Name
- all okay. 因此,如果我只是添加
Name
列-没关系。 But when I want also add image to database there is mistake: 但是当我也想将图像添加到数据库时,会出现错误:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
System.Data.dll中发生类型'System.Data.SqlClient.SqlException'的异常,但未在用户代码中处理
Additional information: Incorrect syntax near the keyword 'Picture'.
附加信息:关键字“图片”附近的语法不正确。
In my local database Picture
have an image
type. 在我的本地数据库中
Picture
具有image
类型。 Please help me. 请帮我。
You need to catch SqlException and then handle it: 您需要捕获SqlException ,然后对其进行处理:
int length = FileUpload.PostedFile.ContentLength;
byte[] picSize = new byte[length];
HttpPostedFile uplImage= FileUpload.PostedFile;
uplImage.InputStream.Read(picSize, 0, length);
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand com = new SqlCommand("INSERT INTO [Table] (Name, Picture) values (@Name, @Picture)", con);
try
{
com.Parameters.AddWithValue("@Name", TextName.Text);
com.Parameters.AddWithValue("@Picture", picSize);
com.ExecuteNonQuery();
}
catch (SqlException ex)
{
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages.Append("Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
Console.WriteLine(errorMessages.ToString());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.