Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save byte[] into a SQL Server database from C#

How can I save a byte[] array into a SQL Server database? This byte[] contains a HashAlgorithm value.

The data is needed again for later use. So converting it and NOT getting it back in its original state, is not what I want.

Thanks in advance!

like image 584
Yustme Avatar asked Oct 30 '10 07:10

Yustme


People also ask

Can I store byte array in SQL?

In Sql Server, use image data type or varbinary data type, to store byte array data.

How can store byte value in SQL Server?

varbinary(max) which is used to store large binary values (BLOBs) up to 2GB. The actual value is stored in a separate location if it's larger than 8000 bytes and just a pointer is stored in the row itself. This type is available since SQL Server 2005. image data type was used to store BLOBs prior to SQL Server 2005.

What is byte array in database?

Byte is an immutable value type that represents unsigned integers with values that range from 0 to 255. You can almost convert any kind of data into Byte Array(Byte []) like File, Image, Xml and etc.. In SQL Server, we have enough datatypes to store string text, int, bool, datatime and even Xml.

How do I save a file to a database?

On the File tab, click Save As. Do one of the following steps: To save a database in a different format, click Save Database As. To save a database object in a different format, click Save Object As.


1 Answers

You should be able to write something like this:

string queryStmt = "INSERT INTO dbo.YourTable(Content) VALUES(@Content)";  using(SqlConnection _con = new SqlConnection(--your-connection-string-here--)) using(SqlCommand _cmd = new SqlCommand(queryStmt, _con)) {    SqlParameter param = _cmd.Parameters.Add("@Content", SqlDbType.VarBinary);    param.Value = YourByteArrayVariableHere;     _con.Open();    _cmd.ExecuteNonQuery();    _con.Close(); } 

Using Linq-to-SQL, you'd write something like this:

using(YourDataContextHere ctx = new YourDataContextHere()) {    SomeClassOfYours item = new SomeClassOfYours();     item.ByteContent = (your byte content here);     ctx.SomeClassOfYourses.InsertOnSubmit(item);    ctx.SubmitChanges(); } 

That will insert your byte[] into a column Content of type VARBINARY in your SQL Server table as a byte stream, which you can read back 1:1 again later on.

like image 161
marc_s Avatar answered Oct 06 '22 00:10

marc_s