2015-09-27 75 views
0

我有在查看故障或從數據庫中顯示的圖像(MySQL的),以datagriview麻煩在顯示圖像的datagridview

我的數據庫中的表,我試圖找回被命名爲樣品與領域ID = INT(10),小學,自動增加和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

首先,你不應該在你的數據庫中存儲圖像。您可以將它們存儲在服務器上,然後使用映像的位置(將映像的存儲位置存儲在數據庫中)進行引用。你能不能顯示你的aspx? –

+0

@AmneshGoel我一直在使用longblob保存和檢索數據庫中的圖像。我還沒有看到你之前說過的任何引用,所以我將它保存在數據庫中。我沒有任何問題,但現在我需要同步我的數據庫,我遇到了這樣的問題:( –

+0

@AmneshGoel,因爲你說的很容易數據丟失,我沒有這樣做 –

回答

0

由於MySql BLOB Type用於存儲SqlServer IMAGE Type我認爲你可以使用MySql類適應這個代碼(即:中MySqlDataAdapter代替SqlDataAdapter):

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

嗨,非常感謝你,我現在可以查看數據網格中的圖像。但你也知道如何將它保存到另一個數據庫?我不能保存任何數據庫:(我會把我目前在我的問題做的代碼 –

+0

如果'DataGridView1'是相同的兩個c ode片段,那麼你在'DataGridView1.Rows(i).Cells(1).Value'中有'Byte()'而不是'String'。 – tezzo