OleDbConnection.ConnectionString 属性

定义

获取或设置用于打开数据库的字符串。Gets or sets the string used to open a database.

public:
 property System::String ^ ConnectionString { System::String ^ get(); void set(System::String ^ value); };
[System.ComponentModel.SettingsBindable(true)]
[System.Data.DataSysDescription("OleDbConnection_ConnectionString")]
public string ConnectionString { get; set; }
member this.ConnectionString : string with get, set
Public Property ConnectionString As String

属性值

OLE DB 提供程序连接字符串,它包括建立初始连接所必需的数据源名称和其他参数。The OLE DB provider connection string that includes the data source name, and other parameters needed to establish the initial connection. 默认值为一个空字符串。The default value is an empty string.

实现

属性

异常

提供了无效的连接字符串参数或未提供所需的连接字符串参数。An invalid connection string argument has been supplied or a required connection string argument has not been supplied.

示例

下面的示例创建一个 OleDbConnection 并在连接字符串中设置它的一些属性。The following example creates an OleDbConnection and sets some of its properties in the connection string.

static void OpenConnection(string connectionString)
{
    using (OleDbConnection connection = new OleDbConnection(connectionString))
    {
        try
        {
            connection.Open();
            Console.WriteLine("ServerVersion: {0} \nDataSource: {1}",
                connection.ServerVersion, connection.DataSource);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        // The connection is automatically closed when the
        // code exits the using block.
    }
}
Public Sub OpenConnection(ByVal connectionString As String)

    Using connection As New OleDbConnection(connectionString)
        Try
            connection.Open()
            Console.WriteLine("Server Version: {0} DataSource: {1}", _
                connection.ServerVersion, connection.DataSource)
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
        ' The connection is automatically closed when the
        ' code exits the Using block.
    End Using
End Sub

注解

ConnectionString 旨在尽可能接近 OLE DB 连接字符串格式,但有以下例外:The ConnectionString is designed to match OLE DB connection string format as closely as possible with the following exceptions:

  • "Provider = value" 子句是必需的。The "Provider = value " clause is required. 但是,不能使用 "Provider = MSDASQL",因为 OLE DB 的 .NET Framework 数据提供程序不支持 ODBC 的 OLE DB 提供程序(MSDASQL)。However, you cannot use "Provider = MSDASQL" because the .NET Framework Data Provider for OLE DB does not support the OLE DB Provider for ODBC (MSDASQL). 若要访问 ODBC 数据源,请使用 System.Data.Odbc 命名空间中的 OdbcConnection 对象。To access ODBC data sources, use the OdbcConnection object that is in the System.Data.Odbc namespace.

  • 与 ODBC 或 ADO 不同,返回的连接字符串与用户设置 ConnectionString相同,如果 Persist Security Info 设置为 false (默认值),则减去安全信息。Unlike ODBC or ADO, the connection string that is returned is the same as the user-set ConnectionString, minus security information if Persist Security Info is set to false (default). OLE DB 的 .NET Framework 数据提供程序不会保留或返回连接字符串中的密码,除非你将 Persist Security Info 关键字设置为 true (不推荐)。The .NET Framework Data Provider for OLE DB does not persist or return the password in a connection string unless you set the Persist Security Info keyword to true (not recommended). 若要保持较高的安全级别,强烈建议使用 Integrated Security 关键字,并将 Persist Security Info 设置为 falseTo maintain a high level of security, it is strongly recommended that you use the Integrated Security keyword with Persist Security Info set to false.

您可以使用 ConnectionString 属性连接到各种数据源。You can use the ConnectionString property to connect to a variety of data sources. 下面的示例演示几个可能的连接字符串。The following example illustrates several possible connection strings.

"Provider=MSDAORA; Data Source=ORACLE8i7;Persist Security Info=False;Integrated Security=Yes"  
  
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\bin\LocalAccess40.mdb"  
  
"Provider=SQLOLEDB;Data Source=(local);Integrated Security=SSPI"  

如果在连接字符串中未指定 Data Source 关键字,则提供程序将尝试连接到本地服务器(如果有)。If the Data Source keyword is not specified in the connection string, the provider will try to connect to the local server if one is available.

有关连接字符串的详细信息,请参阅将连接字符串关键字用于 SQL Server Native ClientFor more information about connection strings, see Using Connection String Keywords with SQL Server Native Client.

仅当关闭连接时,才能设置 ConnectionString 属性。The ConnectionString property can be set only when the connection is closed. 很多连接字符串值都具有对应的只读属性。Many of the connection string values have corresponding read-only properties. 如果设置了连接字符串,则在检测到错误时,将更新这些属性。When the connection string is set, these properties are updated, except when an error is detected. 在这种情况下,不会更新任何属性。In this case, none of the properties are updated. OleDbConnection 属性仅返回 ConnectionString中包含的设置。OleDbConnection properties return only those settings that are contained in the ConnectionString.

重置已关闭连接上的 ConnectionString 将重置所有连接字符串值和相关属性。Resetting the ConnectionString on a closed connection resets all connection string values and related properties. 这包括密码。This includes the password. 例如,如果设置了包含 "初始目录 = AdventureWorks" 的连接字符串,然后将连接字符串重置为 "Provider = SQLOLEDB; Data Source = MySQLServer; IntegratedSecurity = SSPI",则 Database 属性不再设置为 AdventureWorks。For example, if you set a connection string that includes "Initial Catalog= AdventureWorks", and then reset the connection string to "Provider= SQLOLEDB;Data Source= MySQLServer;IntegratedSecurity=SSPI", the Database property is no longer set to AdventureWorks. (连接字符串的初始目录值与 Database 属性相对应。)(The Initial Catalog value of the connection string corresponds to the Database property.)

设置属性时,将执行对连接字符串的初步验证。A preliminary validation of the connection string is performed when the property is set. 如果字符串中包含 ProviderConnect TimeoutPersist Security InfoOLE DB Services 的值,则将检查这些值。If values for the Provider, Connect Timeout, Persist Security Info, or OLE DB Services are included in the string, these values are checked. 当应用程序调用 Open 方法时,将完全验证连接字符串。When an application calls the Open method, the connection string is fully validated. 如果连接字符串包含无效或不受支持的属性,则会生成运行时异常,如 ArgumentExceptionIf the connection string contains invalid or unsupported properties, a run-time exception, such as ArgumentException, is generated.

注意

可以为通用数据链接(UDL)文件中的 OleDbConnection 提供连接信息;但是,应避免这样做。It is possible to supply connection information for an OleDbConnection in a Universal Data Link (UDL) file; however you should avoid doing so. UDL 文件未加密,并以明文形式公开连接字符串信息。UDL files are not encrypted and expose connection string information in clear text. 因为 UDL 文件对您的应用程序来说是一个基于文件的外部资源,所以无法使用 .NET Framework 保护该文件。Because a UDL file is an external file-based resource to your application, it cannot be secured using the .NET Framework.

连接字符串的基本格式包括一系列由分号分隔的关键字/值对。The basic format of a connection string includes a series of keyword/value pairs separated by semicolons. 每个关键字和它的值之间用等号 (=) 连接。The equal sign (=) connects each keyword and its value. 若要包含包含分号、单引号或双引号字符的值,必须将该值用双引号引起来。To include values that contain a semicolon, single-quote character, or double-quote character, the value must be enclosed in double quotation marks. 如果该值同时包含分号和双引号字符,则该值可以用单引号引起来。If the value contains both a semicolon and a double-quote character, the value can be enclosed in single quotation marks. 如果值以双引号字符开头,则单引号也很有用。The single quotation mark is also useful if the value starts with a double-quote character. 相反,如果值以单引号开头,则可以使用双引号。Conversely, the double quotation mark can be used if the value starts with a single quotation mark. 如果该值同时包含单引号和双引号字符,则每次在值中出现时,用来括住该值的引号字符都必须成对出现。If the value contains both single-quote and double-quote characters, the quotation-mark character used to enclose the value must be doubled every time it occurs within the value.

若要在字符串值中包含前导空格或尾随空格,则必须用单引号或双引号将该值引起来。To include preceding or trailing spaces in the string value, the value must be enclosed in either single quotation marks or double quotation marks. 即使用引号引起来,也会忽略整数、布尔值或枚举值前后的任何前导空格或尾随空格。Any leading or trailing spaces around integer, Boolean, or enumerated values are ignored, even if enclosed in quotation marks. 但是,字符串文字关键字或值中的空格将被保留。However, spaces within a string literal keyword or value are preserved. 在不使用分隔符的情况下,可以在连接字符串中使用单引号(例如 Data Source= my'ServerData Source= my"Server),除非引号字符是值中的第一个字符或最后一个字符。Single or double quotation marks may be used within a connection string without using delimiters (for example, Data Source= my'Server or Data Source= my"Server) unless a quotation-mark character is the first or last character in the value.

若要在关键字或值中包含等号(=),则它必须以另一个等号开头。To include an equal sign (=) in a keyword or value, it must be preceded by another equal sign. 例如,在假设的连接字符串中For example, in the hypothetical connection string

"key==word=value"  

关键字为 "key = word",值为 "value"。the keyword is "key=word" and the value is "value".

如果关键字 = 值对中的特定关键字在连接字符串中出现多次,则将在值集中使用最后一次列出的关键字。If a specific keyword in a keyword=value pair occurs multiple times in a connection string, the last occurrence listed is used in the value set.

关键字不区分大小写。Keywords are not case sensitive.

注意

当基于用户输入构造连接字符串时,应小心,例如,从对话框检索用户 ID 和密码信息并将其附加到连接字符串时。You should use caution when constructing a connection string based on user input, for example, when retrieving user ID and password information from a dialog box and appending it to the connection string. 应用程序应确保用户无法在这些值中嵌入其他连接字符串参数,例如,在尝试附加到其他数据库时将密码输入为 "validpassword; database = somedb"。The application should make sure that a user cannot embed additional connection-string parameters in these values, for example, entering a password as "validpassword;database= somedb" in an attempt to attach to a different database. 如果你对 OLE DB 连接使用扩展属性连接字符串参数,则应避免传递用户 Id 和密码,因为如果可能,你应避免以明文形式存储用户 Id 和密码,并且 Persist Security Info= false 的默认设置不会影响 Extended Properties 参数。If you use the Extended Properties connection string parameter for OLE DB connections, avoid passing user IDs and passwords because you should avoid storing user IDs and passwords in clear text if you can, and because the default setting of Persist Security Info= false does not affect the Extended Properties parameter.

适用于

另请参阅