打开单独的 ADO 连接
在某些时候,您可能需要打开和管理自己的 ADO 连接到 SQL Server。例如,您必须使用这种方法,如果您 Access 数据库 (.mdb) 或连接到您的应用程序比另一个 SQL Server 数据库的 Access 项目文件 (.adp) 中编写代码。请注意,使用这种方法时,Microsoft 建议您关闭 ADO 连接打开时不再需要。例如,您可能需要关闭该窗体的 UnLoad 事件在 ADO 连接。
下面的示例演示如何打开自己的 ADO 连接到 Microsoft SQL Server 数据库以及如何将窗体绑定到它︰
-
打开示例数据库 Northwind.mdb。
-
在设计视图中打开客户窗体。
-
清除要取消绑定窗体的窗体的记录源属性。
-
将OnOpen属性的窗体设置为以下事件过程︰
Private Sub Form_Open(Cancel As Integer)
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
'Create a new ADO Connection object
Set cn = New ADODB.Connection
'Use the Access 10 and SQL Server OLEDB providers to
'open the Connection
'You will need to replace MySQLServer with the name
'of a valid SQL Server
With cn
.Provider = "Microsoft.Access.OLEDB.10.0"
.Properties("Data Provider").Value = "SQLOLEDB"
.Properties("Data Source").Value = "MySQLServer"
.Properties("User ID").Value = "sa"
.Properties("Password").Value = ""
.Properties("Initial Catalog").Value = "NorthwindCS"
.Open
End With
'Create an instance of the ADO Recordset class, and
'set its properties
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
.Source = "Select * FROM Customers"
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.Open
End With
'Set the form's Recordset property to the ADO recordset
Set Me.Recordset = rs
Set rs = Nothing
Set cn = Nothing
End Sub
-
将以下代码添加到窗体的 UnLoad 事件︰
Private Sub Form_Unload(Cancel As Integer)
'Close the ADO connection we opened
Dim cn As ADODB.Connection
Set cn = Me.Recordset.ActiveConnection
cn.Close
Set cn = Nothing
End Sub
-
保存该窗体,然后关闭它。
-
在窗体视图中打开客户窗体。
-
添加、 编辑或删除窗体中的记录。
请注意,窗体绑定到可更新记录集基于 SQL Server 数据。
资料来源:
https://support.microsoft.com/zh-cn/kb/281998