專門寫個函數,是返回連接字符串的。你運行好,手頭有。Public Function ConnectString() As String ' Dim p As String ' p = App.Path ' p = p & IIf(Right(p, 1) = "\", "", "\") ' ConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _ ' p & "Test.mdb;Persist Security Info=False"
使用ADO访问sql数据库的简单例子:'引用ADO(Microsoft ActiveX Data Objects 2.X Library) Private Sub Command1_Click() On Error GoTo err Dim cn As New ADODB.Connection, rs As New ADODB.RecordSet '混合验证方式的连接: 'cn.ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=登陆用户名;Password=登录密码;Initial Catalog=数据库名;Data Source=服务器别名" '集成验证的连接: cn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=数据库名;Data Source=服务器别名" cn.Open rs.CursorLocation=adUseClient'设置客户端游标 rs.Open "select * from 表名称", cn, 3, 2 Set DataGrid1.DataSource=rs '把记录显示到DataGrid1里 Exit Sub err: MsgBox err.Description End Sub
cnn.open "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Data Source=pc-17"
ACCESS:
cnn.open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\练习储存\数据库文件\exp.MDB;Persist Security Info=False"
' Dim p As String
' p = App.Path
' p = p & IIf(Right(p, 1) = "\", "", "\")
' ConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
' p & "Test.mdb;Persist Security Info=False"
ConnectString = "Provider=SQLOLEDB.1;" & _
"Persist Security Info=False;" & _
"User ID=?;" & _
"Password=?;" & _
"Initial Catalog=?;" & _
"Data Source=?"
End Function
注釋掉的是連接當前目錄下的ACCESS文件,Test.mdb是文件名
沒注釋掉的是連接SQL的,把?改為相應的參數。
Private Sub Command1_Click()
On Error GoTo err
Dim cn As New ADODB.Connection, rs As New ADODB.RecordSet
'混合验证方式的连接:
'cn.ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=登陆用户名;Password=登录密码;Initial Catalog=数据库名;Data Source=服务器别名"
'集成验证的连接:
cn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=数据库名;Data Source=服务器别名"
cn.Open
rs.CursorLocation=adUseClient'设置客户端游标
rs.Open "select * from 表名称", cn, 3, 2
Set DataGrid1.DataSource=rs '把记录显示到DataGrid1里
Exit Sub
err:
MsgBox err.Description
End Sub