我一直在尝试调整我在网上找到的这个程序的一部分(现在不记得了!)。我一直在尝试使用它来使用BLOB数据类型将图像上传到MYSQL数据库。
Public Sub SQLUpload()
Dim connection As New MySqlConnection(ConnectionImage)
Dim command As New MySqlCommand("INSERT INTO Images (File, FileName, FileSize) VALUES (@Picture, 'Name1', 'Size1')", connection)
'Create an Image object.'
Using picture As Image = Image.FromFile("C:\DIR\Pictures\Person.jpg")
'Create an empty stream in memory.'
Using stream As New IO.MemoryStream
'Fill the stream with the binary data from the Image.'
picture.Save(Stream, Imaging.ImageFormat.Jpeg)
'Get an array of Bytes from the stream and assign to the parameter.'
command.Parameters.AddWithValue("@Picture", SqlDbType.VarBinary).Value = stream.GetBuffer()
End Using
End Using
connection.Open()
Try
command.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
connection.Close()
End Sub
以上是当前的子程序。每当执行此操作时,例程运行正常,直到达到:
Command.ExecuteNonQuery()
它抛出错误:
无法将System.Byte []类型的对象强制转换为System.IConvertible
我很确定这是因为图像中的字节作为数组返回,但是它们保存到的内存不支持数组?这只是通过阅读我在网上其他地方收集而来的。
然而,由于这不是我的所有代码,我坦率地不确定问题是什么。有人能看出它有什么问题吗?
非常感谢
答案 0 :(得分:0)
你在哪里
SqlDbType.VarBinary ' <-- this is Sql Server DB type
使用
MySqlDbType.Blob
喜欢这个
Dim file() As Byte = ' set your file
Dim p As MySqlParameter = new MySqlParameter("@Picture", MySqlDbType.Blob, file.Length)
p.Value = file
command.Parameters.Add(p)
正如其他人所说,你不需要“保存”你的文件 - 只需将其读入字节数组即可。我的代码如下所示:
Public Sub SQLUpload()
Try
Using conn As New MySqlConnection(connString)
' Parametarize entire sql string
Dim sql As String =
"INSERT INTO Images (File, FileName, FileSize) VALUES (@Picture, @name, @size)"
Using cmd As New MySqlCommand(sql, conn)
Dim fileName As String = "C:\DIR\Pictures\Person.jpg"
Dim file() As Byte = File.ReadAllBytes(fileName)
cmd.Parameters.AddWithValue("@Picture", MySqlDbType.Blob).Value = file
cmd.Parameters.AddWithValue("@file", MySqlDbType.VarChar).Value = fileName
cmd.Parameters.AddWithValue("@size", MySqlDbType.Int32).Value = file.Length
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Success")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub