Reputation: 1053
I want to add image from FileUpload
to a local SQL Server database in ASP.NET.
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. 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
Additional information: Incorrect syntax near the keyword 'Picture'.
In my local database Picture
have an image
type. Please help me.
Upvotes: 0
Views: 2321
Reputation: 45490
You need to catch SqlException and then handle it:
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());
}
}
Upvotes: 1