0

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.

2
  • You should check out Can we stop using AddWithValue() already? and stop using .AddWithValue() - it can lead to unexpected and surprising results... Commented Oct 10, 2014 at 18:50
  • image will be removed in a future version of SQL Server. Avoid using this data type in new development work, and plan to modify applications that currently use them. Use varbinary(max) instead. See details here Commented Oct 10, 2014 at 18:53

1 Answer 1

1

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());
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.