inserting an image in to a MySql database

  • Thread starter Thread starter nigelsvision
  • Start date Start date
N

nigelsvision

Guest
Hi,

I am playing about with images. I have created a MySQL database I have 3 columns id, Image1, and name. I want the value of TextBox1 to hold the title of the image and I want the Image1 column to hold the actual image. Im getting the error I have listed below.

Try
Using mySQLcon As New MySqlConnection("server=My working connection here")


End Using
Using command As New MySqlCommand("INSERT INTO Users (name, Image1) VALUES (@name, @Image1)", mySQLcon)
command.Parameters.AddWithValue("@name", TextBox1.Text)
Dim ms As New MemoryStream()
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
Dim data As Byte() = ms.GetBuffer()
Dim p As New MySqlParameter("@Image1", MySqlDbType.Binary)
p.Value = data
cmd.Parameters.Add(p)
cmd.ExecuteNonQuery()
MessageBox.Show("Saved", "Save", MessageBoxButtons.OK)
Label1.Visible = False
TextBox1.Visible = False
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)

End Try

The error im getting is

"Unable to cast object of type 'System.Byte to type 'System.lConvertible' "

I thought I was getting that error because of this line

Dim p As New MySqlParameter("@Image1", MySqlDbType.Binary)

In the example here you can see I have it set to Binary. I have many choices in my MySQL database i.e.

Binary, VarBinary, TinyBlob, MeduimBlob, LongBlob, Blob

I believe LongBlob is limited to 1MB by default which should not be an issue as most of my images are about 170 kb

Thanks Nige

Continue reading...
 
Back
Top