Monday, March 26, 2012

How to insert a byte() to a blob column?

Hi everybody,

I don't where to asked this question in this forum. How do you insert to a column of a table with a blob or binary datatype if there is one, from a byte() datatype? What is wrong? How can I fixed this? I need help. Thanks.

Code:
string sqlText = "Insert table1(id, dataByte) values('" + id + "'," + byteData + ")";

OdbcCommand cmd = new OdbcCommand(sqlText, odConn);

//opening connection here

int iRes = cmd.ExecuteNonQuery();

Result:
iRes = -1
den2005parameterize, parameterize, parameterize
read up on parameters

on a side note - never build sql!
on another side note. . . don't use odbc (there are bugs in the MDAC sql odbc driver)
use oledb. . .
better yet - use the sqlclient library

untested code (might have missed a particular point but this is the gist):



SqlDbCommand cmd = new SqlDbCommand("Insert table1(id, dataByte) values(@.id , @.data)", sqlConn);
cmd.Parameters["@.id"].ParameterValue = id;
cmd.Parameters["@.data"].ParameterValue = byteData;
int iRes = cmd.ExecuteNonQuery()

Research "how to store an image in a database" - its the same concept.
Again. . . parameterize your queries.
Insist that your peers do the same.

Security - Performance - Maintainence

and this question belongs in .Net Data Access Forum|||Thanks for reply, Blair Allen. I solved this my problem now is retrieving this BLOB from database and converting it to byte() and loading it to a Micorosft.Ink object using Ink.Load() method. The error occurs at Ink.Load() statement. Can anyone help? Thanks for advise. I'll post this problem at .Net Data Access Forum.

den2005|||I think this is it:
just hacked, not checked


byte[] bytes = null;
/* first get the size. . . */
int num = MySqlDataReader.GetBytes("myBlobField", 0, null, 0, int.MaxValue);
if (num != 0)
{
/* allocate the bytes */
bytes = new byte[num];
/* load the bytes */
MySqlDataReader.GetBytes("myBlobField", 0, bytes, 0,num)
}

cheers|||Thanks Blair Allen for reply I used a different approach. I converted the byte() to a base64 string format and then store it as a Text data in database and retrieving it as string and used Convert.FromBase64String() method to convert it back to byte() and load it to Ink.Load() and it works.

den2005

No comments:

Post a Comment