如何建立VB的Access数据库连接模块,怎么调用这个模块

2024-12-01 07:50:36
推荐回答(1个)
回答1:

'在模块中添加以下代码------------------

Public cn As New ADODB.Connection
Public rs As New ADODB.Recordset

'连接数据库
Public Function ConnectDB(strDb as string) As String
On Error GoTo ErrH:

With cn

If .State <> adStateClosed Then .Close

.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strDb &";"

.ConnectionTimeout = 30

.CursorLocation = adUseClient

.Open

End With

Exit Function
ErrH:

ConnectDB = "连接数据库失败:" & Err.Description
End Function

'程序启动函数
Sub Main()
dim strResult as string
dim strDatabase as String
'数据库路径
strDataBase=App.Path & "test.db"
strResult=ConnectDB()

'连接数据库
if strResult<>"" then

Msgbox strResult,vbCritical

End
End If
MsgBox "连接数据库成功!"

'打开数据表(Table1是你的数据表)
rs.Open "select * from Table1",cn,adOpenKeyset, adLockOptimistic
MsgBox "共找到"& rs.RecordCount &"条记录!"
rs.Close
End Sub