我在查看或显示从数据库(mysql)到datagriview的图像时遇到了麻烦
我尝试检索的数据库中的表格被命名为示例,字段 ID = Int(10),主要,自动增量和< strong> IMG = blob
任何可以帮助我的人?非常感谢
Sub getData()
Try
Dim Sql = "Select ID, IMG from sample"
connectionOn()
Dim cmd = New MySqlCommand(Sql, ConOn)
Dim dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
DataGridView1.Rows.Clear()
While dr.Read = True
Dim mybytearray As Byte() = dr.Item("IMG")
Dim myimage As Image
Dim ms As System.IO.MemoryStream = New System.IO.MemoryStream(mybytearray)
myimage = System.Drawing.Image.FromStream(ms)
DataGridView1.Rows.Add(dr(0), myimage)
End While
ConOn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
以下是我在数据库中保存图像的代码。但它并没有拯救任何东西。我想从datagrid获取图像,然后将其保存到数据库
Try
connectionSync()
Dim a, b As String
Dim Sql = "INSERT INTO SAMPLE (ID, IMG)values(@a,@b)"
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
a = Me.DataGridView1.Rows(i).Cells(0).Value.ToString()
Dim cmd As New MySqlCommand(Sql, ConSync)
Dim memorystream1 As New MemoryStream()
Dim filename As String = DataGridView1.Rows(i).Cells(1).Value
Dim bitmaps As New Bitmap(filename)
bitmaps.Save(memorystream1, Imaging.ImageFormat.Jpeg)
Dim pic() As Byte = memorystream1.GetBuffer()
cmd.Parameters.AddWithValue("@a", a)
cmd.Parameters.AddWithValue("@b", bitmaps)
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
Next
ConSync.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
答案 0 :(得分:0)
由于MySql BLOB Type用于存储SqlServer IMAGE Type
,我认为您可以使用MySql
类(即:MySqlDataAdapter
而不是SqlDataAdapter
)调整此代码:< / p>
Try
Me.DataGridView1.DataSource = Nothing
Dim dgvID As New DataGridViewTextBoxColumn
dgvID.DataPropertyName = "ID"
Dim dgvIMG As New DataGridViewImageColumn
dgvIMG.DataPropertyName = "IMG"
Me.DataGridView1.Columns.Add(dgvID)
Me.DataGridView1.Columns.Add(dgvIMG)
connectionOn()
Dim cmdSample As SqlCommand = ConOn.CreateCommand
cmdSample.CommandText = "SELECT ID, " _
& "IMG " _
& "FROM Sample"
Dim dtSample As New DataTable
Dim daSample As New SqlDataAdapter(cmdSample)
daSample.Fill(dtSample)
Me.DataGridView1.DataSource = dtSample
ConOn.Close()
ConOn.Dispose()
Catch ex As Exception
MsgBox(ex.Message)
End Try