0

I want to store the image(any type of image) into the database by using varbinary(MAX).

My Database:

CREATE TABLE [dbo].[Pic]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY, 
    [picture] VARBINARY(MAX) NULL, 
    [origin] NVARCHAR(100) NULL
)

My code:

protected void Button1_Click(object sender, EventArgs e)
{
    byte[] imagebyte = File.ReadAllBytes(Server.MapPath("~/") + imageUpload1);

    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "insert into Pic values('"+ imagebyte +"','"+ lblOrigin.Text +"')";
    cmd.ExecuteNonQuery();
}

when I run my code, I get this error:

Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. at cmd.ExecuteNonQuery();

How can I solve this problem?

2
  • 1
    Images are binary. The problem is that you're using string concatenation to create queries, something that exposes you to SQL injection attacks, conversion errors and actually makes it impossible to pass dates, numbers or ... images without conversion issues. Use parameterized queries instead. Commented Nov 27, 2019 at 8:31
  • Does this answer your question? How to insert PictureBox to Sql Server Database Varbinary(MAX) with C#? Commented Nov 27, 2019 at 8:32

2 Answers 2

2

Always use parameterized sql queries, to retrieve data, but also to store data. This will prevent SQL injection attacks from happening, and will enable you to store (large) binary objects in your database.

using (SqlCommand cmd = con.CreateCommand()) {
  cmd.CommandType = CommandType.Text;
  cmd.CommandText = "insert into Pic (picture, origin) values(@image, @origin)";

  // cmd.Parameters.AddWithValue("@image", imagebyte);
  cmd.Parameters.Add("@image", SqlDbType.VarBinary);
  cmd.Parameters["@image"].Value = imagebyte;

  cmd.Parameters.AddWithValue("@origin", lblOrigin.Text);
  cmd.ExecuteNonQuery();
}
Sign up to request clarification or add additional context in comments.

1 Comment

AddWithValue is dangerous as string concatenation. In this case it will assume that the actual parameter size equals the length of the values, whether it does or not. This can easily lead to truncation
0

Here is a resource for you to look at. I think this will solve your problem.

Just a note: Use stored procedures when doing operations on a database in your code.

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.