views:

3706

answers:

3

Hi there,

I have a byte array highlighted below, how do I insert it into a SQL Server database Varbinary column?

byte[] arraytoinsert = new byte[10]{0,1,2,3,4,5,6,7,8,9,10};

string sql = 
    string.format
    (
    "INSERT INTO mssqltable (varbinarycolumn) VALUES ({0});",WHATTODOHERE
    );

Thanks in advance guys!

+6  A: 

Try this:

"0x" + BitConverter.ToString(arraytoinsert).Replace("-", "")

Although you should really be using a parameterised query rather than string concatenation of course...

David M
+1: Use parameters.
Richard
Hi David, thanks for the answer, why should I be using a parameterised query?
divinci
Minimal here, but parameterised queries can be compiled and then cached, saving the cost of compilation with each subsequent query. They also protect against SQL injection attacks. Finally, you can set the value of the parameter to the byte array directly and avoid the BitConverter stuff...
David M
Don't think working with VARBINARIES like this is good idea in general. SQL Server allows very large VARBINARIES (was it 2 Gb?) and that would probably not "scale very well" with this method. Can't assess if this would be a problem in this particular case, so I'm leaving off the -1 for now.
peSHIr
@peSHIr: -1 for whom? All I did was to answer the question that was asked...
David M
+2  A: 

My solution would be to use a parameterised query, as the connectivity objects take care of formatting the data correctly (including ensuring the correct data-type, and escaping "dangerous" characters where applicable):

// Assuming "conn" is an open SqlConnection
using(SqlCommand cmd = new SqlCommand("INSERT INTO mssqltable(varbinarycolumn) VALUES (@binaryValue)", conn))
{
    // Replace 8000, below, with the correct size of the field
    cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary, 8000).Value = arraytoinsert;
    cmd.ExecuteNonQuery();
}

Edit: Added the wrapping "using" statement as suggested by John Saunders to correctly dispose of the SqlCommand after it is finished with

Jason Musgrove
Jason, could you please put a using statement around "SqlCommand cmd = new ..."? Otherwise, I'll feel obligated to downvote, and I'd hate that.
John Saunders
A: 

No problem if all the arrays you are about to use in this scenario are small like in your example.

If you will use this for large blobs (e.g. storing large binary files many Mbs or even Gbs in size into a VARBINARY) then you'd probably be much better off using specific support in SQL Server for reading/writing subsections of such large blobs. Things like READTEXT and UPDATETEXT, or in current versions of SQL Server SUBSTRING.

For more information and examples see either my 2006 article in .NET Magazine ("BLOB + Stream = BlobStream", in Dutch, with complete source code), or an English translation and generalization of this on CodeProject by Peter de Jonghe. Both of these are linked from my weblog.

peSHIr