'讀入檔案資料
Dim fs = New FileStream("c:\1.jpg", IO.FileMode.Open, IO.FileAccess.Read)
Dim imgData(fs.Length - 1) As Byte
fs.Read(imgData, 0, fs.Length - 1)
fs.close()
Dim tempConnection As New SqlConnection
Dim tempAdapter As SqlDataAdapter
Dim tempDataSet As New DataSet
'開啟資料庫連接
tempConnection.ConnectionString = "server=s_Test;uid=sa;pwd=7890;database=db_test"
tempConnection.Open()
tempAdapter = New SqlDataAdapter("SELECT * FROM tb_test WHERE 1=0", tempConnection)
Dim cb As New SqlCommandBuilder(tempAdapter)
tempAdapter.Fill(tempDataSet)
'插入一條記錄
Dim tempDataRow As DataRow
tempDataRow = tempDataSet.Tables(0).NewRow()
tempDataRow("photo") = imgData
tempDataSet.Tables(0).Rows.Add(tempDataRow)
tempAdapter.Update(tempDataSet)
tempConnection.Close()
End Sub
End Class
二、將資料庫中的檔案儲存至硬碟(VB.NET)
Dim tempConnection As New SqlConnection
Dim tempAdapter As SqlDataAdapter
Dim tempDataSet As New DataSet
'開啟資料庫連接,取出資料
tempConnection.ConnectionString = "server=s_test;uid=sa;pwd=7890;database=db_test"
tempConnection.Open()
tempAdapter = New SqlDataAdapter("SELECT TOP 1 * FROM tb_test", tempConnection)
tempAdapter.Fill(tempDataSet)
tempConnection.Close()
If tempDataSet.Tables(0).Rows.Count > 0 Then
'將檔案儲存到硬碟檔案c:\2.jpg
Dim imgData() As Byte
imgData = tempDataSet.Tables(0).Rows(0).Item("photo")
Dim fs As FileStream
fs = File.Create("c:\2.jpg", imgData.Length - 1)
fs.Write(imgData, 0, imgData.Length - 1)
fs.Close()
End If
End Sub
End Class
'讀取檔案
Dim fs = New System.IO.FileStream("c:\2.jpg", IO.FileMode.Open, IO.FileAccess.Read)
Dim imgData(fs.Length - 1) As Byte
fs.Read(imgData, 0, fs.Length - 1)
fs.close()
Dim tempConnection As New SqlConnection
Dim tempAdapter As SqlDataAdapter
Dim tempDataSet As New DataSet
'開啟資料庫連接,取出資料
tempConnection.ConnectionString = "server=s_test;uid=sa;pwd=7890;database=db_test"
tempConnection.Open()
tempAdapter = New SqlDataAdapter("SELECT TOP 1 * FROM tb_test", tempConnection)
tempAdapter.Fill(tempDataSet)
'更新資料
Dim cb As New SqlCommandBuilder(tempAdapter)
tempDataSet = New DataSet
tempAdapter.Fill(tempDataSet)
tempDataSet.Tables(0).Rows(0).Item("photo") = imgData
tempAdapter.Update(tempDataSet)
tempConnection.Close()
End Sub
End Class