This post is part of the SQLStringBuilder project. For the latest version of the code i suggest to take the source code from the CVS.

Today at work i had my daily dilemma: how can i save a blob field in a MySQL DB with c#??? The solution it’s pretty simple, but it can be hard to find.

The Blob is a binary field where data can be saved: the problem is that we must write these binary data in a textual SQL string. To resolve this problem we can convert the binary data in an hexadecimal representation in order to write the data in a textual format.

Binary data

The resulting SQL will look like that:

INSERT INTO tableWithBlob VALUES(1,0xab425fa52d3e13);

Where 0x… are our binary data.

To start, we must first convert the data structure that we want to put in the database in a byte array (byte[]), or in a format in which we can access all structure’s bytes.

At this time to create the blob field to insert in the SQL string, we can use the following code stub:

byte [] blob = // binary data to save in the db

// create a StringBuider with the required space to allocate the hexadecimal blob.
// plus the first two characters (0x)
StringBuilder blobBuilder = new StringBuilder(blob.Length + 2);
blobBuilder.Append(”0x”);

// convert every byte in a hexadecimal char and append it to the StringBuilder
for (int i = 0; i < blob.Length; i++)
	blobBuilder.Append(String.Format(”{0:x2}”, blob[i]));

string blobString = retBlob.ToString();

Simply, it’s not??

kick it on DotNetKicks.com


Se sei interessato a questo post, potresti anche provare a leggere:

  • No related posts