0

I'm trying to update a varbinary in my MSSQL with a binary array of an image. I tried using this query, which doesn't seem to work:

string sql = "UPDATE table SET bdata='" + imagedata + "' WHERE ID=1";

This is just an example of a query I used. Why doesn't it work? And I prefer not using SqlCommand.

bdata is of type varbinary(max) and imagedata is a byte array.

What am I doing wrong that it's not working? An exception tells me I need to use CONVERT or something like that..

This is the given exception when trying to run it:

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

Omer Aviv
  • 286
  • 3
  • 20
  • What do you mean by _doesn't seem to work_? You get any exception or error message? You need to use `+` just before `WHERE ID=1` as well. Also you should use it in a string like `+ WHERE ID=1` (WHERE ID=1 part should beetween `"` since it is a string) – Soner Gönül May 18 '15 at 08:47
  • What is the type of `imagedata`? If you "*prefer not using SqlCommand*" - then how do you executing your query? Add more details. – Andrey Korneyev May 18 '15 at 08:49
  • Added variable types. – Omer Aviv May 18 '15 at 08:54
  • I do use SqlCommand but in another class that I trigger by sending a string of the query I want. – Omer Aviv May 18 '15 at 08:55
  • Use parameters! Then you can just set the parameter value to a `byte[]` rather than messing with strings like you are here, that's also open to injection! – Lloyd May 18 '15 at 08:56
  • But how can I send it like what I have done? With `"bdata='" + imagedata + "'"` – Omer Aviv May 18 '15 at 08:57
  • First, *never* construct SQL statements by concatenating strings. There are various security and performance issues. Second, you can't pass a byte array as a string. Use parameterized queries as shown in the duplicate question and pass the byte[] value to a SqlDbType.VarBinary typed parameter. – Panagiotis Kanavos May 18 '15 at 09:10
  • I managed doing it while sending the query and a `SqlParameterCollection` to the update method. Thanks! – Omer Aviv May 18 '15 at 11:48

0 Answers0