工程-引用-找到Microsoft ActiveX Data Objects Library
下面的示例代码以Northwinds数据库作为远程数据源,然后用ADO来访问它。首先在控制面板中打开“32位数据源”,单击“添加”按钮。在弹出的对话框中选择 "Microsoft ACCESS Driver (*.mdb)" 作为数据源驱动程序。
选择数据库Northwinds所在路径。单击完成,退出ODBC设备管理器。
启动一个新的VB工程,在窗体的Load事件中输入下面的代码:
Private Sub Form_Load()
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
'Set Connection properties
cn.ConnectionString = "DSN=RDC Nwind;UID=;PWD=;"
cn.ConnectionTimeout = 30
cn.Open
If cn.State = adStateOpen Then _
MsgBox "Connection to NorthWind Successful!"
cn.Close
End Sub
按F5运行程序,看看,一个消息框弹出来告诉你连接成功了。请注意,这里我特别注明了是ADODB.Connection,而不是ADOR.Connection,这样做是为了将二者区分开(如果你引用了ADODB和ADOR的话,这样做很有必要)。连接字符串看上去同RDO的连接字符串差不多。事实上,二者确实差不多。
如果我们要访问一个SQL Server数据库,你的Connection代码看上去应象下面所示:
'设置连接属性cn.Provider = "MSDASQL"
cn.ConnectionString = "driver={SQL Server};" & "server=prod1;uid=bg;pwd=;database=main"
cn.Open
"Provider"属性指向SQL Server的OLE DB Provider.
回到我们的示例程序,让我们创建一个Recordset对象来访问“Orders”表,并从该表的"ShipCountry"字段中产生头十个不重复的国家名。修改窗体Load事件中的代码,让它看上去象下面这样。
Private Sub Form_Load()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sSQL As String
Dim sOut As String
Dim Count As Integer
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Set properties of the Connection.
cn.ConnectionString = "DSN=RDC Nwind;UID=;PWD=;"
cn.ConnectionTimeout = 30
cn.Open
If cn.State = adStateOpen Then _
MsgBox "Connection to NorthWind Successful!"
sSQL = "SELECT DISTINCT Orders.ShipCountry FROM Orders"
Set rs = cn.Execute(sSQL)
'Enumerate the recordset
sOut = ""
For Count = 1 To 10
sOut = sOut & rs("ShipCountry") & VBCrLf
rs.MoveNext
Next Count
MsgBox sOut, VBExclamation, "ADO Results"
cn.Close
End Sub
不幸的是,目前这个Recrodset对象是只读的和forward cursor。如果你想要获取更多的功能,你需要创建一个独立的Recordset对象,该对象拥有自己的Connection属性,就象下面的代码所示:
Private Sub Form_Load()
Dim rs As ADODB.Recordset
Dim sSQL As String
Dim sOut As String
Dim Count As Integer
Set rs = New ADODB.Recordset
sSQL = "SELECT DISTINCT Orders.ShipCountry FROM Orders"
rs.Open sSQL, "DSN=RDC Nwind;UID=;PWD=;", adOpenDynamic
'Report Recordset Connection information
MsgBox rs.ActiveConnection, , "Connection Info"
'Enumerate the recordset
sOut = ""
For Count = 1 To 10
sOut = sOut & rs("ShipCountry") & VBCrLf
rs.MoveNext
Next Count
MsgBox sOut, VBExclamation, "ADO Results"
rs.Close
End Sub
上面代码返回的结果同前例一样,但是本代码中的Recordset是独立的。这一点是DAO和RDO做不到的。Recordset对象的Open方法打开一个代表从SQL查询返回的记录的游标。虽然你可以用Connection对象同远程数据源建立连接,但请记住,在这种情况下,Connection对象和Recordset对象是平行的关系。