*************************************************************************
'**
'** 使用 ADODB.Stream 儲存/讀取檔案到資料庫
'** 引用 Microsoft ActiveX Data Objects 2.5 Library 及以上版本
'**
'** ----- 資料庫連接字串模板 ---------------------------------------
'** ACCESS資料庫
'** iConcStr = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False" & _
'** ";Data Source=資料庫名"
'**
'** SQL資料庫
'** iConcStr = "Provider=SQLOLEDB.1;Persist Security Info=True;" & _
'** "User ID=使用者名稱;Password=密碼;Initial Catalog=資料庫名;Data Source=SQL伺服器名"
'**
'*************************************************************************
'
'儲存檔案到資料庫中
Sub s_SaveFile()
Dim iStm As ADODB.Stream
Dim iRe As ADODB.Recordset
Dim iConcStr As String
'資料庫連接字串
iConcStr = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False" & _
";Data Source=F:\My Documents\客戶資料1.mdb"
'讀取檔案到內容
Set iStm = New ADODB.Stream
With iStm
.Type = adTypeBinary '二進位模式
.Open
.LoadFromFile "c:\test.doc"
End With
'開啟儲存檔案的表
Set iRe = New ADODB.Recordset
With iRe
.Open "表", iConc, adOpenKeyset, adLockOptimistic
.AddNew '新增一條記錄
.Fields("儲存檔案內容的欄位") = iStm.Read
.Update
End With
'完成後關閉對象
iRe.Close
iStm.Close
End Sub
'從資料庫中讀取資料,儲存成檔案
Sub s_ReadFile()
Dim iStm As ADODB.Stream
Dim iRe As ADODB.Recordset
Dim iConc As String
'資料庫連接字串
iConc = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False" & _
";Data Source=\\xz\c$\Inetpub\zj\zj\zj.mdb"
'開啟表
Set iRe = New ADODB.Recordset
iRe.Open "tb_img", iConc, adOpenKeyset, adLockReadOnly
iRe.Filter = "id=64"
'儲存到檔案
Set iStm = New ADODB.Stream
With iStm
.Mode = adModeReadWrite
.Type = adTypeBinary
.Open
.Write iRe("img")
.SaveToFile "c:\test.doc"
End With
'關閉對象
iRe.Close
iStm.Close
End Sub