2008年9月8日 星期一

vb.net圖片進出資料庫

'--------------------把照片擺進資料庫'
Dim dteStart As DateTime = Now
Dim cn As New IfxConnection(strCN)
Dim pic_byte = My.Computer.FileSystem.ReadAllBytes("c:\1.jpg")
Dim connectStringBuilder As New OleDb.OleDbConnectionStringBuilder()
Using con As IfxConnection = New IfxConnection(connectStringBuilder.ConnectionString) ' 新增資料記錄的 INSERT 陳述式
Dim insertStr As String = _
"INSERT INTO test (ser_no , pic ) VALUES (" & _ " '2' , ? )"
' 使用 SqlCommand 類別的第三個建構函式來建立 SqlCommand 物件
' 並將內含參數的 INSERT 陳述式指派給 SqlCommand 物件
Dim insertCMD As New IfxCommand(insertStr, cn)
' 於參數集合中替各個參數加入一個參數物件並設定這些參數的值
' 於參數集合中參數 @ThumbNailPhoto 加入一個參數物件並設定其值
insertCMD.Parameters.Add("?ThumbnailPhotoFileName", SqlDbType.Image, pic_byte.Length).Value = pic_byte
'MsgBox(insertStr)
' 開啟連接
insertCMD.Connection.Open()
' 執行資料命令來新增資料記錄
insertCMD.ExecuteNonQuery()
insertCMD.Connection.Close()
pic_byte = Nothing
Pibox.Image = Nothing
End Using
'Dim TS As TimeSpan = Now.Subtract(dteStart)
'MsgBox("執行時間: " & TS.TotalMilliseconds & " 毫秒")
'-----------------------------把照片讀出來
Dim Cn As New IfxConnection(strCN)
Dim Da As New IfxDataAdapter(strSQL, Cn)
Dim Cmd As New IfxCommand(strSQL, Cn)
Dim DS As New DataSet
strSQL = "SELECT * FROM test WHERE ser_no = 2"
Cmd.CommandText = strSQL
Da.SelectCommand = Cmd
Cmd.Connection.Open()
Da.Fill(DS)
Cmd.Connection.Close()
If Not IsDBNull(DS.Tables(0).Rows(0).Item(1)) Then
Try
Dim tmpImageFile As String = My.Computer.FileSystem.GetTempFileName
My.Computer.FileSystem.WriteAllBytes(tmpImageFile, DS.Tables(0).Rows(0).Item(1), False)
Me.Pibox.Image = Image.FromFile(tmpImageFile) My.Computer.FileSystem.DeleteFile(tmpImageFile)
Catch ex As Exception
End Try
Else
Me.Pibox.Image = Nothing
End If

沒有留言:

張貼留言