Workspace.OpenDatabase 方法 (DAO)

适用于:Access 2013、Office 2013

打开 Workspace 对象中指定的数据库并返回对表示该数据库的 Database 对象的引用。

语法

表达式 。OpenDatabase (名称选项ReadOnlyConnect)

表达式 一个表示 Workspace 对象的变量。

参数

名称

必需/可选

数据类型

说明

Name

必需

String

现有 Microsoft Access 数据库引擎数据库文件的名称或 ODBC 数据源的数据源名称 (DSN)。 有关设置此值的详细信息,请参阅 Name 属性。

选项

可选

Variant

设置数据库的各种选项(如“说明”中所述)。

ReadOnly

可选

Variant

如果要使用只读访问权限打开数据库,此值为 True;如果要使用可读写访问权限打开数据库,此值为 False(默认值)。

Connect

可选

Variant

指定各种连接信息,包括密码。

返回值

Database

说明

可以为 Options 参数使用如下值。

Setting

说明

True

以独占模式打开数据库。

False

(默认)以共享模式打开数据库。

打开数据库时会自动将该数据库添加到 Databases 集合。

使用 dbname 时有以下适用的注意事项:

  • 如果它引用了已打开以便由其他用户访问的数据库,则会发生错误。

  • 如果它没有引用现有数据库或有效的 ODBC 数据源名称,则会发生错误。

  • 如果它是零长度字符串 (""),并且 connect 为 "ODBC;",则会显示列出所有已注册 ODBC 数据源名称的对话框,以便用户能够选择数据库。

若要关闭一个数据库,并因此从 Databases 集合中删除 Database 对象,请对该对象使用 Close 方法。

注意

[!注释] 在访问 Microsoft Access 数据库引擎连接的 ODBC 数据源时,可通过打开连接到 ODBC 数据源的 Database 对象改善应用程序的性能,这样不需要将单个 TableDef 对象链接到 ODBC 数据源中的特定表。

示例

以下示例使用 OpenDatabase 方法打开一个 Microsoft Access 数据库和两个连接到 Microsoft Access 数据库引擎的 ODBC 数据库。

Sub OpenDatabaseX() 
 
 Dim wrkAcc As Workspace 
 Dim dbsNorthwind As Database 
 Dim dbsPubs As Database 
 Dim dbsPubs2 As Database 
 Dim dbsLoop As Database 
 Dim prpLoop As Property 
 
 ' Create Microsoft Access Workspace object. 
 Set wrkAcc = CreateWorkspace("", "admin", "", dbUseJet) 
 
 ' Open Database object from saved Microsoft Access database 
 ' for exclusive use. 
 MsgBox "Opening Northwind..." 
 Set dbsNorthwind = wrkAcc.OpenDatabase("Northwind.mdb", _ 
 True) 
 
 ' Open read-only Database object based on information in 
 ' the connect string. 
 MsgBox "Opening pubs..." 
 
 ' Note: The DSN referenced below must be set to 
 ' use Microsoft Windows NT Authentication Mode to 
 ' authorize user access to the Microsoft SQL Server. 
 Set dbsPubs = wrkAcc.OpenDatabase("Publishers", _ 
 dbDriverNoPrompt, True, _ 
 "ODBC;DATABASE=pubs;DSN=Publishers") 
 
 ' Open read-only Database object by entering only the 
 ' missing information in the ODBC Driver Manager dialog 
 ' box. 
 MsgBox "Opening second copy of pubs..." 
 Set dbsPubs2 = wrkAcc.OpenDatabase("Publishers", _ 
 dbDriverCompleteRequired, True, _ 
 "ODBC;DATABASE=pubs;DSN=Publishers;") 
 
 ' Enumerate the Databases collection. 
 For Each dbsLoop In wrkAcc.Databases 
 Debug.Print "Database properties for " & _ 
 dbsLoop.Name & ":" 
 
 On Error Resume Next 
 ' Enumerate the Properties collection of each Database 
 ' object. 
 For Each prpLoop In dbsLoop.Properties 
 If prpLoop.Name = "Connection" Then 
 ' Property actually returns a Connection object. 
 Debug.Print " Connection[.Name] = " & _ 
 dbsLoop.Connection.Name 
 Else 
 Debug.Print " " & prpLoop.Name & " = " & _ 
 prpLoop 
 End If 
 Next prpLoop 
 On Error GoTo 0 
 
 Next dbsLoop 
 
 dbsNorthwind.Close 
 dbsPubs.Close 
 dbsPubs2.Close 
 wrkAcc.Close 
 
End Sub