Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I save an 'Object' in a SQL Server database?

I want to save an object (of any type) into a field in a database in SQL Server 2005. Is it possible? Do I have to convert the object into something, like a byte array for example and cast it back when retrieving it?

like image 202
Ahmad Farid Avatar asked Aug 19 '09 11:08

Ahmad Farid


People also ask

How do you store objects in a database?

You can store objects in relational tables as column objects or in object tables as row objects. Those objects that have meaning outside of the relational database they reside in, should be made referenceable as row objects in an object table. Otherwise, they should be stored as column objects in a relational table.

What can be stored in a SQL database?

A database can also contain other objects including views, stored procedures, indexes and constraints, in addition to tables, along with a transaction log. A SQL Server database can contain a maximum of 231 objects, and can span multiple OS-level files with a maximum file size of 220 TB.

Can we save file in SQL Server?

You will need to attach it to your SQL Server. The files will be read into a File Stream and then the File Stream will be converted into byte array using BinaryReader in order to save into the database table. Once the File is converted into Byte Array it will be inserted into the database.

Can you store JSON in SQL?

SQL Server and Azure SQL Database have native JSON functions that enable you to parse JSON documents using standard SQL language. You can store JSON documents in SQL Server or SQL Database and query JSON data as in a NoSQL database.


2 Answers

You can use the VARBINARY(MAX) field type in SQL Server, if you like. You can store any type of object in there, up to 2 GB in size.

To access it, you can use ADO.NET - something like this:

object yourMysteryObject = (whatever you like it to be);  MemoryStream memStream = new MemoryStream(); StreamWriter sw = new StreamWriter(memStream);  sw.Write(yourMysteryObject);  SqlCommand sqlCmd = new SqlCommand("INSERT INTO TableName(VarBinaryColumn) VALUES (@VarBinary)", sqlConnection);  sqlCmd.Parameters.Add("@VarBinary", SqlDbType.VarBinary, Int32.MaxValue);  sqlCmd.Parameters["@VarBinary"].Value = memStream.GetBuffer();  sqlCmd.ExecuteNonQuery(); 

Marc

like image 67
marc_s Avatar answered Sep 25 '22 20:09

marc_s


I would use JSON to convert the object to a string, and store it in a VARCHAR or TEXT field. Not only the data is stored in a human-readable format, but it's also also readable from different languages, since pretty much every mainstream language has a JSON parser available.

The link I posted has links to several libraries in many languages (including C#), I have used this one a couple times in the past.

like image 26
Badaro Avatar answered Sep 24 '22 20:09

Badaro