mysql - 将图像保存到 mysql 数据库时出现问题。程序运行完美,没有错误
问题描述
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
那么您还应该指定一个尺寸。
推荐阅读
- java - Ghidra 的 JDK 给我错误:“找不到或加载主类 LaunchSupport”
- javascript - 尝试使用应用程序脚本在 html 中的表格中添加工作表中的数据
- macos - 在 macOS Quicklook 预览中显示实际文件图标
- c++ - 带有 lambda 的 noexcept 运算符。MSVC 错误?
- networking - 创建 pnet 数据链路通道时出现 Rust 错误“PermissionDenied: Operation Not Permitted”
- javascript - 如何为表格研究显示消息“未找到结果”?
- php - 多个限制,其中价格 1 <> 价格 2
- nginx - Drone CI/CD 登录失败。我的虚拟机上的无效响应
- java - “使用名称创建 bean 时出错......”它发生在 MongoRepository 的一个实例中,我使用的是 Java11 和 springboot
- ios - 播放使用 AVCaptureAudioDataOutput 录制的音频