首页 > 解决方案 > 将图像保存到 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

标签: mysqlsqlvb.net

解决方案


这是错误的:

command.Parameters.AddWithValue("@img", SqlDbType.Image).Value = ms.ToArray()

您正在混合和匹配两种不同的添加参数的方式。如果您调用AddWithValue(通常不应该调用),那么您需要提供一个值,而不是类型。如果您要指定一个类型,然后设置它Value,那么您调用Add.

另外,SqlDBType是用于SqlClient和 SQL Server 的。如果您使用的是MySqlClientMySQL,那么您需要使用MySqlDbType. 这是一个完美的例子,说明你为什么需要Option Strict On在那里。

你的代码应该是这样的:

command.Parameters.Add("@img", MySqlDbType.Blob).Value = ms.ToArray()

我说“类似这样的东西”是因为您指定的类型取决于您在数据库中使用的实际数据类型。如果您需要使用,VarBinary那么您还应该指定一个尺寸。


推荐阅读