2015-07-12 55 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

相關問題