Issue with dynamically contruct an INSERT statement - using vb code - that uploads a file into a database

Ok, here an issue I'm facing here:

As part of the project requirements I'm working on I need to upload a file to a database tabl, and to dynamically build my INSERT statement that uploads that file using vb.net.

Here is what I have:

I have a database table called "Attachments", it's design is as follows:

Column (1) Label = "ID"
Column (1) type = PRIMARY KEY
Column (1) Data-Type = "int"


Column (2) Label = "AttachmentContent"
Column (2) type = NORMAL
Column (2) Data-Type = "varbinary(MAX)"


So now, if I want to insert a record into this table, I can do so like this in my VB code:

Dim MC as new MainClass
MC.DB("INSERT INTO Attachments (AttachmentContent) VALUES (XXXXXXXXXXXXXXXXXXXXXXX)")

Open in new window


See attachment "DB_CLASS.txt" that defines "MainClass"

Now, my issue is with the XXXXXXXXXXXXXXXXXXXXXXX above in my code

I tried to do it this way:

Dim filePath As String = "C:\Some_File.gif"
Dim fs As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read)
Dim br As BinaryReader = New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(Convert.ToInt32(fs.Length))
br.Close()
fs.Close()
MC.DB("INSERT INTO Attachments (AttachmentContent) VALUES ('"+bytes.toString+"')")

Open in new window


It gives me an error because the insert statement that the system tries to execute becomes like this at run time:

INSERT INTO Attachments (AttachmentContent) VALUES ('System.Byte[]')

Open in new window


What am I missing here?
DB_CLASS.txt
Hussein ZahranAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Karthik RamachandranCommented:
Try something like this
query = "INSERT INTO student (AttachmentContent) VALUES (@AttachmentContent)"
Using conn as New SqlConnection("connectionStringHere")
    Using comm As New SqlCommand()
        With comm
            .Connection = conn
            .CommandType = CommandType.Text
            .CommandText = query
            .Parameters.AddWithValue("@AttachmentContent", bytes.toString())
        End With
                Try
                    conn.open()
                    comm.ExecuteNonQuery()
                Catch(ex as SqlException)
                    MessageBox.Show(ex.Message.ToString(), "Error Message")
                End Try
    End Using
End USing

Open in new window

Hussein ZahranAuthor Commented:
I'm not allowed to execute the SQL statement like this due to some other requirements. Therefore; I mentioned that I need to construct the SQL statement through concatenaiton of strings.

So, all I need is how do I pass the bytes into the "INSERT INTO Attachments (AttachmentContent) VALUES (XXXXXXXXXXXXXXXXXXXXXXX)" string in place of the 'XXXXXXXXXXXXXXXXXXXXXXX'
Hussein ZahranAuthor Commented:
Just to further explain why I can't use the code you're suggesting is that because I don't have access to change the definition of the MainClass.DB method, and that MainClass.DB method is the only way I can read/write from/to a database, and I'm not allowed to create my own method to read/write from/to a database.
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

louisfrCommented:
To get a string out of a byte array, you need to use the correct Encoding object.
If your array contains UTF-8 bytes, you can get the string with:
Dim decodedString = Encoding.UTF8.GetString(bytes)

Open in new window

Hussein ZahranAuthor Commented:
Louisfr

I tried what you suggested like this:

"INSERT INTO Attachments (AttachmentContent) VALUES (System.Text.Encoding.UTF8.GetString(bytes))"

Open in new window


it gave me an error, I think my MC.DB() method expects something like this format "0x424D2E30140000.....etc." for the [AttachmentContent] column in Attachments table

Any idea?
Hussein ZahranAuthor Commented:
I got it, the following function converts my "bytes" variable into a hexadec. format:

    Private Function BytesToString(ByVal Input As Byte()) As String
        Dim Result As New System.Text.StringBuilder(Input.Length * 2)
        Dim Part As String
        For Each b As Byte In Input
            Part = Conversion.Hex(b)
            If Part.Length = 1 Then Part = "0" & Part
            Result.Append(Part)
        Next
        Return "0x" + Result.ToString()
    End Function

Open in new window


It works now

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Hussein ZahranAuthor Commented:
I searched further in the net and I found this solution which now works for me
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.