2015-07-12 56 views
2

我一直在尝试调整我在网上找到的这个程序的一部分(现在不记得!)。我一直在尝试使用这种方式将图像上传到MYSQL数据库使用BLOB数据类型。使用BLOB抛出异常将图像上传到数据库

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() 

它引发错误:

Unable to cast object of type System.Byte[] to type System.IConvertible

我敢肯定,这是因为一个事实,即从图像中的字节作为数组返回,但是它们保存的内存不支持数组?这只是从我在网上其他地方完成的阅读中收集的。

但是,由于这不是我所有的代码,我坦率地不确定问题是什么。任何人都可以看到它有什么问题吗?

非常感谢

回答

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) 

正如其他人所说,你并不需要“保存“你的文件 - ju st读入字节数组。我的代码如下所示:

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 
+0

MySql vs SQL Server类型的优点。 – Plutonix

相关问题