Imports MySql.Data.MySqlClient Imports System.IO Public Class Form1 Dim connection As New MySqlConnection("server=Localhost;userid=root;password=root;database=image") Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim opf As New OpenFileDialog opf.Filter = "Choose Image(*.JPF;*.PNG;*.GIF)|*.jpg;*.png;*.gif" If opf.ShowDialog = Windows.Forms.DialogResult.OK Then PictureBox1.Image = Image.FromFile(opf.FileName) End If End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim command As New MySqlCommand("insert into saveimage(image) values(@img)", connection) Dim ms As New MemoryStream PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat) command.Parameters.AddWithValue("@img", SqlDbType.Image).Value = ms.ToArray() connection.Open() MessageBox.Show("Insert image") End Sub End Class
Advertisement
Answer
This is wrong:
command.Parameters.AddWithValue("@img", SqlDbType.Image).Value = ms.ToArray()
You are mixing and matching two different ways of adding parameters. If you call AddWithValue
(which you generally should not) then you need to provide a value, not a type. If you’re going to specify a type and then set the Value
afterwards then you call Add
.
Also, SqlDBType
is for SqlClient
and SQL Server. If you’re using MySqlClient
and MySQL then you need to use MySqlDbType
. That’s a perfect example of why you need Option Strict On
right there.
Your code should be something like this:
command.Parameters.Add("@img", MySqlDbType.Blob).Value = ms.ToArray()
I say “something like this” because what type you specify depends on the actual data type you used in the database. If you need to use VarBinary
then you should also specify a size.