Friday, March 30, 2012

reading / writing binary data to db

I'm trying to read a byte array of an image datatype from sql server, and then to put this in another field in the database. I get a byte array, but somehow the image doesn't get into the db well with the sql parameters. Does anyone have an idea how to tackle this problem?

Thanks a lot, Hugohttp://www.dotnetspider.com/Technology/QA/ViewQuestion.aspx?QuestionId=117

I think that link above has the answers to your question. Make sure you're using Image type, and passing in the byte array, and that you don't have anything blocking your connection (firewall or switch that's set to cap communication sizes).

Otherwise, I don't know what to tell ya. Need to see code.|||Thanks for the link, it helps me somehow although not enough, however...

Basically, what I'm trying to do is to "pump" binary data from one field in one table to another field in another table (both are of the image data type, length 16).

What I have now, is a byte array read from the original field, and set it as a value of an SqlParameter to insert it into the new field. This is the code fragment:


Dim SQLSel As String = "SELECT imgImage FROM tblProducts WHERE autoProductID=" & CategoryID

Dim reader As SqlClient.SqlDataReader
reader = _data.sqlRetrieveDataReader(SQLSel) 'retrieve a data reader via DAL
reader.Read()

'set the binary data of the original image in the byte array
Dim b() As Byte = CType(reader.GetValue(0), Byte())
Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream(b, True)
stream.Write(b, 0, b.Length)

'insert the byte array into the new parameter
sqlComInsert.Parameters.Item("@.imgImage").Value = b

No errors are trapped when this code is executed. However, only red crossed (i.e. bad images) are displayed in the browser. The following code is used to display images from the database (which has proven to work on the original images/binary data):


Dim ProductID As String = Request.QueryString("ProductID")
Dim conn As New SqlClient.SqlConnection(CType(configurationAppSettings.GetValue("sqlConn.ConnectionString", GetType(System.String)), String))
Dim SQLSel As String = "SELECT imgImage FROM tblProducts WHERE autoProductID=" & CategoryID
Dim com As New SqlClient.SqlCommand(SQLSel, conn)
conn.Open()
Try
Response.ContentType = "image/gif"
Response.BinaryWrite(com.ExecuteScalar)
Response.End()
Finally
conn.Close()
End Try

I really have no clue what causes the movement of the images/binary data via asp.net to fail... if anyone knows how to tackle this problem, please help. Thanks a lot in advance, Hugo

No comments:

Post a Comment