简体   繁体   中英

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.

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.

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());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM