2011年7月26日 星期二

資料庫存取文件

'** 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

沒有留言:

張貼留言