Wednesday, 28 March 2007

MySQL - Uploading binary data

Believe it or not, alot of people have trouble with this and it can be quite confusing but here I am again to make it easy for you all. This post will explain how to upload binary data successfully to a MySQL database and the binary data can be anything from a picture to an MP3 file.

In this example, I have a page with a FileUpload component and a button. Paste the following code into the button_click event or write a seperate function to call:

Dim myConnection As New MySql.Data.MySqlClient.MySqlConnection
myConnection.ConnectionString = "Server=
MYSERVER;User Id=MYUSER;Password=MYPASS;Persist Security Info=True;Database=MYDATABASE"
Dim mycommand As New MySql.Data.MySqlClient.MySqlCommand
mycommand.Connection = myConnection
Dim strsql
strsql = "INSERT INTO `mydb`.`mytable` (`Document` ) VALUES (?file);"
mycommand.Parameters.Add("?file", FileUpload1.FileBytes)
mycommand.CommandText = strsql

As usual, fill out the bold text correctly. Easy huh?

No comments: