'Vb/VBA for Database File Access
'The example database is an Access database. If you use the SQL database, you only need to change the connection string.
'
'*************************************** **********************************
'**
'** Use ADODB. Stream to save/read files to the database
'** Reference Microsoft ActiveX Data Objects 2.5 library and later
'**
'** ----- Database connection string template ---------------------------------------
'** Access Database
'** Iconcstr = "provider = Microsoft. Jet. oledb.4.0; persist Security info = false "&_
'** "; Data Source = database name"
'**
'** SQL database
'** Iconcstr = "provider = sqloledb.1; persist Security info = true ;"&_
'** "User ID = user name; Password = password; initial catalog = database name; Data Source = SQL server name"
'**
'*************************************** **********************************
'
'Save the file to the database.
Sub s_savefile ()
Dim istm as ADODB. Stream
Dim ire as ADODB. recordset
Dim iconcstr as string
'Access database connection string
Iconcstr = "provider = Microsoft. Jet. oledb.4.0; persist Security info = false "&_
"; Data Source = F: My Documents ents customer profile 1.mdb"
'SQL database connection string
Iconcstr = "provider = sqloledb.1; persist Security info = true ;"&_
"User ID = user name; Password = password; initial catalog = database name; Data Source = SQL server name"
'Read the file to the content
Set istm = new ADODB. Stream
With istm
. Type = adtypebinary 'binary mode. If you use the text/ntext field to save plain text data, use adtypetext.
. Open
. Loadfromfile "C: est.doc"
End
'Open the table that saves the file
Set ire = new ADODB. recordset
With ire
. Open "table", iconc, adopenkeyset, adlockoptimistic
. Addnew' adds a record.
. Fields ("field for saving file content") = istm. Read
. Update
End
'Close the object after completion
Ire. Close
Istm. Close
End sub
'Read data from the database and save it as a file
Sub s_readfile ()
Dim istm as ADODB. Stream
Dim ire as ADODB. recordset
Dim iconc as string
'Database connection string
Iconc = "provider = Microsoft. Jet. oledb.4.0; persist Security info = false "&_
"; Data Source =/xzc $ inetpubzjzjzj. mdb"
'Open a table
Set ire = new ADODB. recordset
Ire. Open "tb_img", iconc, adopenkeyset, adlockreadonly
Ire. Filter = "id = 64"
If ire ("IMG"). actualsize> 0 then
'Save to file
Set istm = new ADODB. Stream
With istm
. Mode = admodereadwrite
. Type = adtypebinary 'binary mode. If you use the text/ntext field to save plain text data, use adtypetext.
. Open
. Write ire ("IMG ")
. Savetofile "C: est.doc"
End
'Close the object
Istm. Close
End if
Ire. Close
End sub