0

I am trying to store an image into a SQL Server database. I keep getting the error around cmd.ExecuteNonQuery().

string fileName = ofd.FileName;

SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = @"Server = Big-PAPI-PC\SQLEXPRESS; Database = LOGO; Trusted_Connection = True";

cnn.Open();

// inserts image and name
string prompt_id = txt_result.ToString();
Image image = pictureBox1.Image;

string query = $"INSERT INTO dbo.LOGO (Logo_Prompt,image) VALUES({ prompt_id} , {image})";

SqlCommand cmd = new SqlCommand(query, cnn);
cmd.ExecuteNonQuery();

// Insertservice(prompt_id,image);
MessageBox.Show("Item inserted  !");
cnn.Close();
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

You should parameterize your queries:

string query = "INSERT INTO dbo.LOGO (Logo_Prompt,image) VALUES(@prompt_id, @image)";
SqlCommand cmd = new SqlCommand(query, cnn);
cmd.Parameters.AddWithValue("@prompt_id", prompt_id);
cmd.Parameters.AddWithValue("@image", image);

And as @marc_s suggests better pass parameters with explicit db type:

command.Parameters.Add("@prompt_id", SqlDbType.....).Value = prompt_id;
command.Parameters.Add("@image", SqlDbType.....).Value = image;
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 5
    **Parametrize - YES!!** But you should check out [Can we stop using AddWithValue() already?](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) and stop using `.AddWithValue()` - it can lead to unexpected and surprising results... – marc_s Jun 06 '20 at 20:58