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
这是错误的:
command.Parameters.AddWithValue("@img", SqlDbType.Image).Value = ms.ToArray()
你是混合和匹配添加参数的两种不同的方式。如果调用AddWithValue
(你一般不应其中),那么你需要提供一个值,而不是一个类型。如果你要指定一个类型,然后设置Value
事后然后调用Add
。
此外,SqlDBType
是SqlClient
和SQL Server。如果你使用MySqlClient
和MySQL,那么你需要使用MySqlDbType
。这就是为什么你需要Option Strict On
右边有一个很好的例子。
你的代码应该是这样的:
command.Parameters.Add("@img", MySqlDbType.Blob).Value = ms.ToArray()
我说:“这样的事情”,因为什么类型指定取决于你在数据库中实际使用的数据类型。如果你需要使用VarBinary
那么你也应该指定一个尺寸。