SqlConnection.ConnectionString Property

Definition

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

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

Property Value

String

连接字符串,其中包含源数据库名称和建立初始连接所需的其他参数。The connection string that includes the source database name, and other parameters needed to establish the initial connection. 默认值为空字符串。The default value is an empty string.

Implements

Attributes

Exceptions

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

Examples

下面的示例创建一个 SqlConnection,并在打开连接之前设置 ConnectionString 属性。The following example creates a SqlConnection and sets the ConnectionString property before opening the connection.

private static void OpenSqlConnection()
{
    string connectionString = GetConnectionString();

    using (SqlConnection connection = new SqlConnection())
    {
        connection.ConnectionString = connectionString;

        connection.Open();

        Console.WriteLine("State: {0}", connection.State);
        Console.WriteLine("ConnectionString: {0}",
            connection.ConnectionString);
    }
}

static private string GetConnectionString()
{
    // To avoid storing the connection string in your code,
    // you can retrieve it from a configuration file.
    return "Data Source=MSSQL1;Initial Catalog=AdventureWorks;"
        + "Integrated Security=true;";
}
Private Sub OpenSqlConnection()
    Dim connectionString As String = GetConnectionString()

    Using connection As New SqlConnection()

        connection.ConnectionString = connectionString

        connection.Open()

        Console.WriteLine("State: {0}", connection.State)
        Console.WriteLine("ConnectionString: {0}", _
            connection.ConnectionString)
    End Using
End Sub

Private Function GetConnectionString() As String
    ' To avoid storing the connection string in your code,  
    ' you can retrieve it from a configuration file.
    Return "Data Source=MSSQL1;Database=AdventureWorks;" _
      & "Integrated Security=true;"
End Function

Remarks

ConnectionString 类似于 OLE DB 连接字符串,但并不完全相同。The ConnectionString is similar to an OLE DB connection string, but is not identical. 与 OLE DB 或 ADO 不同,返回的连接字符串与用户设置 ConnectionString相同,如果 "持久安全信息" 值设置为 false (默认值),则减去安全信息。Unlike OLE DB or ADO, the connection string that is returned is the same as the user-set ConnectionString, minus security information if the Persist Security Info value is set to false (default). SQL Server 的 .NET Framework 数据提供程序不会保留或返回连接字符串中的密码,除非你将持久性安全信息设置为 trueThe .NET Framework Data Provider for SQL Server does not persist or return the password in a connection string unless you set Persist Security Info to true.

您可以使用 ConnectionString 属性连接到数据库。You can use the ConnectionString property to connect to a database. 下面的示例演示了一个典型的连接字符串。The following example illustrates a typical connection string.

"Persist Security Info=False;Integrated Security=true;Initial Catalog=Northwind;server=(local)"

使用新 SqlConnectionStringBuilder 在运行时构造有效的连接字符串。Use the new SqlConnectionStringBuilder to construct valid connection strings at run time. 有关详细信息,请参阅连接字符串生成器For more information, see Connection String Builders.

仅当关闭连接时,才能设置 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. SqlConnection 属性仅返回 ConnectionString中包含的设置。SqlConnection properties return only those settings that are contained in the ConnectionString.

若要连接到本地计算机,请为服务器指定 "(local)"。To connect to a local computer, specify "(local)" for the server. 如果未指定服务器名称,则将尝试连接到本地计算机上的默认实例。If a server name is not specified, a connection will be attempted to the default instance on the local computer.

重置已关闭连接上的 ConnectionString 将重置所有连接字符串值(以及相关属性),包括密码。Resetting the ConnectionString on a closed connection resets all connection string values (and related properties) including the password. 例如,如果设置了包含 "Database = AdventureWorks" 的连接字符串,然后将连接字符串重置为 "Data Source = myserver; 集成安全性 = true",则 Database 属性将不再设置为 "AdventureWorks"。For example, if you set a connection string that includes "Database= AdventureWorks", and then reset the connection string to "Data Source=myserver;Integrated Security=true", the Database property is no longer set to "AdventureWorks".

设置后,将立即分析连接字符串。The connection string is parsed immediately after being set. 如果在分析时发现语法错误,则会生成运行时异常,如 ArgumentExceptionIf errors in syntax are found when parsing, a runtime exception, such as ArgumentException, is generated. 只有在尝试打开连接时,才能找到其他错误。Other errors can be found only when an attempt is made to open the connection.

连接字符串的基本格式包括一系列由分号分隔的关键字/值对。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'Server 或 Data 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.

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

下表列出了 ConnectionString中的关键字值的有效名称。The following table lists the valid names for keyword values within the ConnectionString.

关键字Keyword 默认Default 说明Description
AddrAddr 不可用N/A 数据源的同义词。Synonym of Data Source.
AddressAddress 不可用N/A 数据源的同义词。Synonym of Data Source.
应用程序App 不可用N/A 应用程序名称的同义词。Synonym of Application Name.
应用程序名称Application Name 不可用N/A 应用程序的名称,如果未提供应用程序名称,则为 ".NET SQLClient Data Provider"。The name of the application, or '.NET SQLClient Data Provider' if no application name is provided.

应用程序名称的长度不能超过128个字符。An application name can be 128 characters or less.
ApplicationIntent ReadWrite 连接到服务器时声明应用程序工作负荷类型。Declares the application workload type when connecting to a server. 可能值为 ReadOnlyReadWritePossible values are ReadOnly and ReadWrite. 例如:For example:

ApplicationIntent=ReadOnly

有关对 Always On 可用性组的 SqlClient 支持的详细信息,请参阅对高可用性、灾难恢复的 SqlClient 支持For more information about SqlClient support for Always On Availability Groups, see SqlClient Support for High Availability, Disaster Recovery.
Asynchronous ProcessingAsynchronous Processing

- 或 --or-

AsyncAsync
false'false' true时,将启用异步操作支持。When true, enables asynchronous operation support. 已识别的值为 truefalseyesnoRecognized values are true, false, yes, and no.

.NET Framework 4.5.NET Framework 4.5 开始时,忽略此属性。This property is ignored beginning in .NET Framework 4.5.NET Framework 4.5. 有关异步编程的 SqlClient 支持的详细信息,请参阅异步编程For more information about SqlClient support for asynchronous programming, see Asynchronous Programming.
AttachDBFilenameAttachDBFilename

- 或 --or-

扩展属性Extended Properties

- 或 --or-

初始文件名Initial File Name
不可用N/A 主数据库文件的名称,包括可附加数据库的完整路径名。The name of the primary database file, including the full path name of an attachable database. 仅支持具有 .mdf 扩展名的主数据文件的 AttachDBFilename。AttachDBFilename is only supported for primary data files with an .mdf extension.

如果在连接字符串中指定了 AttachDBFileName 键的值,则附加数据库并成为连接的默认数据库。If the value of the AttachDBFileName key is specified in the connection string, the database is attached and becomes the default database for the connection.

如果未指定此键,并且以前附加了数据库,则将不会重新附加该数据库。If this key is not specified and if the database was previously attached, the database will not be reattached. 以前附加的数据库将用作连接的默认数据库。The previously attached database will be used as the default database for the connection.

如果将此密钥与 AttachDBFileName 键一起指定,则此项的值将用作别名。If this key is specified together with the AttachDBFileName key, the value of this key will be used as the alias. 但是,如果该名称已在另一附加数据库中使用,则连接将失败。However, if the name is already used in another attached database, the connection will fail.

路径可以是绝对路径或相对路径,方法是使用 DataDirectory 替换字符串。The path may be absolute or relative by using the DataDirectory substitution string. 如果使用了 DataDirectory,则数据库文件必须存在于替换字符串指向的目录的子目录中。If DataDirectory is used, the database file must exist within a subdirectory of the directory pointed to by the substitution string. 注意: 远程服务器、HTTP 和 UNC 路径名称不受支持。Note: Remote server, HTTP, and UNC path names are not supported.

数据库名称必须用关键字 "database" (或它的一个别名)指定,如下所示:The database name must be specified with the keyword 'database' (or one of its aliases) as in the following:

"AttachDbFileName=|DataDirectory|\data\YourDB.mdf;integrated security=true;database=YourDatabase"

如果日志文件和数据文件存在于同一个目录中,并且在附加主数据文件时使用“database”关键字,则将生成错误。An error will be generated if a log file exists in the same directory as the data file and the 'database' keyword is used when attaching the primary data file. 在这种情况下,请移除日志文件。In this case, remove the log file. 附加数据库后,将基于物理路径自动生成一个新日志文件。Once the database is attached, a new log file will be automatically generated based on the physical path.
身份验证Authentication 不可用N/A 用于通过使用 Azure Active Directory 身份验证连接到 SQL 数据库的身份验证方法。The authentication method used for Connecting to SQL Database By Using Azure Active Directory Authentication.

有效值是:Valid values are:

Active Directory 集成,Active Directory 密码,Sql 密码。Active Directory Integrated, Active Directory Password, Sql Password.
列加密设置Column Encryption Setting 不可用N/A 启用或禁用连接的Always Encrypted功能。Enables or disables Always Encrypted functionality for the connection.
连接超时值Connect Timeout

- 或 --or-

Connection TimeoutConnection Timeout

- 或 --or-

超时Timeout
1515 在终止尝试并生成错误之前等待连接到服务器的时间长度(以秒为单位)。The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.

有效值大于或等于0且小于或等于2147483647。Valid values are greater than or equal to 0 and less than or equal to 2147483647.

打开到 Azure SQL 数据库的连接时,将连接超时值设置为30秒。When opening a connection to a Azure SQL Database, set the connection timeout to 30 seconds.
连接生存期Connection Lifetime

- 或 --or-

Load Balance TimeoutLoad Balance Timeout
00 连接返回到池中后,创建时间将与当前时间进行比较,如果时间跨度(秒)超过 Connection Lifetime 指定的值,该连接将被破坏。When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by Connection Lifetime. 在聚集配置中可以使用它来强制在运行服务器和刚联机的服务器之间达到负载平衡。This is useful in clustered configurations to force load balancing between a running server and a server just brought online.

如果值为零(0),则池连接的最大连接超时。A value of zero (0) causes pooled connections to have the maximum connection timeout.
ConnectRetryCountConnectRetryCount 11 控制客户端标识空闲连接失败后的重新连接尝试次数。Controls the number of reconnection attempts after the client identifies an idle connection failure. 有效值为0至255。Valid values are 0 to 255. 默认值为 1。The default is 1. 0表示不尝试重新连接(禁用连接复原)。0 means do not attempt to reconnect (disable connection resiliency).

若要详细了解空闲连接复原,请参阅技术文章 - 空闲连接复原For additional information about idle connection resiliency, see Technical Article - Idle Connection Resiliency.
ConnectRetryIntervalConnectRetryInterval 1010 指定每次连接重试尝试(ConnectRetryCount)之间的时间。Specifies the time between each connection retry attempt (ConnectRetryCount). 有效值为1到60秒(默认值 = 10),在第一次重新连接尝试之后应用。Valid values are 1 to 60 seconds (default=10), applied after the first reconnection attempt. 检测到断开连接时,客户端会立即尝试重新连接;这是第一次重新连接尝试,并且仅当 ConnectRetryCount 大于0时才会发生。When a broken connection is detected, the client immediately attempts to reconnect; this is the first reconnection attempt and only occurs if ConnectRetryCount is greater than 0. 如果第一次重新连接尝试失败并且 ConnectRetryCount 大于1,则客户端将等待 ConnectRetryInterval 尝试再次重新连接尝试。If the first reconnection attempt fails and ConnectRetryCount is greater than 1, the client waits ConnectRetryInterval to try the second and subsequent reconnection attempts.

若要详细了解空闲连接复原,请参阅技术文章 - 空闲连接复原For additional information about idle connection resiliency, see Technical Article - Idle Connection Resiliency.
Context ConnectionContext Connection false'false' true 是否应建立与 SQL Server 的进程内连接。true if an in-process connection to SQL Server should be made.
Current LanguageCurrent Language

- 或 --or-

LanguageLanguage
不可用N/A 设置用于数据库服务器警告或错误消息的语言。Sets the language used for database server warning or error messages.

语言名称长度不能超过128个字符。The language name can be 128 characters or less.
数据源Data Source

- 或 --or-

ServerServer

- 或 --or-

AddressAddress

- 或 --or-

AddrAddr

- 或 --or-

网络地址Network Address
不可用N/A 要连接到的 SQL Server 实例的名称或网络地址。The name or network address of the instance of SQL Server to which to connect. 端口号可以在服务器名称之后指定:The port number can be specified after the server name:

server=tcp:servername, portnumber

指定本地实例时,始终使用(local)。When specifying a local instance, always use (local). 若要强制使用协议,请添加以下前缀之一:To force a protocol, add one of the following prefixes:

np:(local), tcp:(local), lpc:(local)

.NET Framework 4.5.NET Framework 4.5开始,还可以连接到 LocalDB 数据库,如下所示:Beginning in .NET Framework 4.5.NET Framework 4.5, you can also connect to a LocalDB database as follows:

server=(localdb)\\myInstance

有关 LocalDB 的详细信息,请参阅SqlClient 对 localdb 的支持For more information about LocalDB, see SqlClient Support for LocalDB.

数据源必须使用 TCP 格式或命名管道格式。Data Source must use the TCP format or the Named Pipes format.

TCP 格式如下所示:TCP format is as follows:

-tcp:<主机名 >\< 实例名称>- tcp:<host name>\<instance name>
-tcp:<主机名 >,<TCP/IP 端口号 >- tcp:<host name>,<TCP/IP port number>

TCP 格式必须以前缀 "TCP:" 开头,后面是由主机名和实例名指定的数据库实例。The TCP format must start with the prefix "tcp:" and is followed by the database instance, as specified by a host name and an instance name. 连接到 Azure SQL 数据库时,此格式不适用。This format is not applicable when connecting to Azure SQL Database. 如果未指定协议,则会自动选择 TCP 连接到 Azure SQL 数据库。TCP is automatically selected for connections to Azure SQL Database when no protocol is specified.

必须通过以下方式之一指定主机名:The host name MUST be specified in one of the following ways:

- NetBIOSName- NetBIOSName
- IPv4Address- IPv4Address
- IPv6Address- IPv6Address

实例名称用于解析数据库实例所托管的特定 TCP/IP 端口号。The instance name is used to resolve to a particular TCP/IP port number on which a database instance is hosted. 另外,也允许直接指定 TCP/IP 端口号。Alternatively, specifying a TCP/IP port number directly is also allowed. 如果实例名称和端口号不存在,则使用默认数据库实例。If both instance name and port number are not present, the default database instance is used.

命名管道格式如下所示:The Named Pipes format is as follows:

-np:\\< 主机名>\pipe\< 管道名称>- np:\\<host name>\pipe\<pipe name>

命名管道格式必须以前缀 "np:" 开头并且后跟命名管道名称。The Named Pipes format MUST start with the prefix "np:" and is followed by a named pipe name.

必须通过以下方式之一指定主机名:The host name MUST be specified in one of the following ways:

- NetBIOSName- NetBIOSName
- IPv4Address- IPv4Address
- IPv6Address- IPv6Address

管道名称用于标识将 .NET Framework 应用程序连接到的数据库实例。The pipe name is used to identify the database instance to which the .NET Framework application will be connected.

如果指定网络密钥的值,则不应指定前缀 "tcp:" 和 "np:"。If the value of the Network key is specified, the prefixes "tcp:" and "np:" should not be specified. 注意: 你可以通过在连接字符串中将tcp: 作为服务器名的前缀,或使用localhost来强制使用 tcp 而不是共享内存。Note: You can force the use of TCP instead of shared memory, either by prefixing tcp: to the server name in the connection string, or by using localhost.
加密Encrypt false'false' true时,如果服务器安装了证书,则 SQL Server 对客户端和服务器之间发送的所有数据使用 SSL 加密。When true, SQL Server uses SSL encryption for all data sent between the client and server if the server has a certificate installed. 已识别的值为 truefalseyesnoRecognized values are true, false, yes, and no. 有关详细信息,请参阅连接字符串语法For more information, see Connection String Syntax.

.NET Framework 4.5.NET Framework 4.5开始,当 TrustServerCertificate 为 false 并且 Encrypt 为 true 时,SQL Server SSL 证书中的服务器名称(或 IP 地址)必须与连接字符串中指定的服务器名称(或 IP 地址)完全匹配。Beginning in .NET Framework 4.5.NET Framework 4.5, when TrustServerCertificate is false and Encrypt is true, the server name (or IP address) in a SQL Server SSL certificate must exactly match the server name (or IP address) specified in the connection string. 否则,连接尝试将失败。Otherwise, the connection attempt will fail. 有关使用者以通配符(*)开头的证书支持的详细信息,请参阅服务器证书用于服务器身份验证的接受通配符For information about support for certificates whose subject starts with a wildcard character (*), see Accepted wildcards used by server certificates for server authentication.
登记Enlist 'true''true' true 指示 SQL Server 连接池程序在创建线程的当前事务上下文中自动登记连接。true indicates that the SQL Server connection pooler automatically enlists the connection in the creation thread's current transaction context.
Failover PartnerFailover Partner 不可用N/A 配置了数据库镜像的故障转移伙伴服务器的名称。The name of the failover partner server where database mirroring is configured.

如果此项的值为 "",则必须存在初始目录,并且其值不能为 ""。If the value of this key is "", then Initial Catalog must be present, and its value must not be "".

服务器名称的长度不能超过128个字符。The server name can be 128 characters or less.

如果你指定故障转移伙伴,但没有为数据库镜像配置故障转移伙伴服务器,并且主服务器(使用 Server 关键字指定)不可用,则连接将失败。If you specify a failover partner but the failover partner server is not configured for database mirroring and the primary server (specified with the Server keyword) is not available, then the connection will fail.

如果你指定故障转移伙伴并且没有为数据库镜像配置主服务器,则在主服务器可用时,与主服务器(使用 Server 关键字指定)的连接将成功。If you specify a failover partner and the primary server is not configured for database mirroring, the connection to the primary server (specified with the Server keyword) will succeed if the primary server is available.
Initial CatalogInitial Catalog

- 或 --or-

数据库Database
不可用N/A 数据库的名称。The name of the database.

数据库名称的长度不能超过128个字符。The database name can be 128 characters or less.
Integrated SecurityIntegrated Security

- 或 --or-

Trusted_ConnectionTrusted_Connection
false'false' false时,在连接中指定用户 ID 和密码。When false, User ID and Password are specified in the connection. true时,将使用当前的 Windows 帐户凭据进行身份验证。When true, the current Windows account credentials are used for authentication.

识别的值为 truefalseyesnosspi (强烈建议),这与 true等效。Recognized values are true, false, yes, no, and sspi (strongly recommended), which is equivalent to true.

如果指定了用户 ID 和密码,并将 "集成安全性" 设置为 "true",则将忽略用户 ID 和密码,并使用集成安全性。If User ID and Password are specified and Integrated Security is set to true, the User ID and Password will be ignored and Integrated Security will be used.

SqlCredential 是一种更安全的方式,用于为使用 SQL Server 身份验证(Integrated Security=false)的连接指定凭据。SqlCredential is a more secure way to specify credentials for a connection that uses SQL Server Authentication (Integrated Security=false).
最大池大小Max Pool Size 100100 池中允许的最大连接数。The maximum number of connections that are allowed in the pool.

有效值大于或等于1。Valid values are greater than or equal to 1. 小于最小池大小的值会生成错误。Values that are less than Min Pool Size generate an error.
Min Pool SizeMin Pool Size 00 池中允许的最小连接数。The minimum number of connections that are allowed in the pool.

有效值大于或等于0。Valid values are greater than or equal to 0. 此字段中的零(0)表示最初没有打开最小值连接。Zero (0) in this field means no minimum connections are initially opened.

大于最大池大小的值会生成错误。Values that are greater than Max Pool Size generate an error.
MultipleActiveResultSetsMultipleActiveResultSets false'false' true时,应用程序可以维护多个活动的结果集(MARS)。When true, an application can maintain multiple active result sets (MARS). false时,应用程序必须处理或取消一个批处理中的所有结果集,然后才能对该连接执行任何其他批处理。When false, an application must process or cancel all result sets from one batch before it can execute any other batch on that connection.

已识别的值为 truefalseRecognized values are true and false.

有关详细信息,请参阅多个活动结果集 (MARS)For more information, see Multiple Active Result Sets (MARS).
MultiSubnetFailover FALSEFALSE 连接到 SQL Server 2012 (或更高版本)可用性组或 SQL Server 2012 (或更高版本)故障转移群集实例的可用性组侦听器时,应始终指定 multiSubnetFailover=TrueAlways specify multiSubnetFailover=True when connecting to the availability group listener of a SQL Server 2012 (or later) availability group or a SQL Server 2012 (or later) Failover Cluster Instance. multiSubnetFailover=True 配置 SqlClient 以更快地检测和连接到(当前)活动服务器。multiSubnetFailover=True configures SqlClient to provide faster detection of and connection to the (currently) active server. 可能的值包括 YesNoTrueFalse10Possible values are Yes and No, True and False or 1 and 0. 例如:For example:

MultiSubnetFailover=True

默认为 FalseThe default is False. 有关 SqlClient 对 Always On Ag 的支持的详细信息,请参阅SqlClient 对高可用性、灾难恢复的支持For more information about SqlClient's support for Always On AGs, see SqlClient Support for High Availability, Disaster Recovery.
Network LibraryNetwork Library

- 或 --or-

网络Network

- 或 --or-

NetNet
不可用N/A 用于建立与 SQL Server 实例的连接的网络库。The network library used to establish a connection to an instance of SQL Server. 支持的值包括:Supported values include:

dbnmpntw (命名管道)dbnmpntw (Named Pipes)

dbmsrpcn (多协议,Windows RPC)dbmsrpcn (Multiprotocol, Windows RPC)

dbmsadsn (Apple 交谈)dbmsadsn (Apple Talk)

dbmsgnet (通过)dbmsgnet (VIA)

dbmslpcn (共享内存)dbmslpcn (Shared Memory)

dbmsspxn (IPX/SPX)dbmsspxn (IPX/SPX)

dbmssocn (TCP/IP)dbmssocn (TCP/IP)

Dbmsvinn (Banyan Vines)Dbmsvinn (Banyan Vines)

必须在系统上安装您要连接到的相应网络 DLL。The corresponding network DLL must be installed on the system to which you connect. 如果未指定网络,并且你使用的是本地服务器(例如,"." 或 "(local)"),则使用共享内存。If you do not specify a network and you use a local server (for example, "." or "(local)"), shared memory is used. 在此示例中,网络库是 Win32 Winsock TCP/IP (dbmssocn),1433 是使用的端口。In this example, the network library is Win32 Winsock TCP/IP (dbmssocn), and 1433 is the port being used.

Network Library=dbmssocn;Data Source=000.000.000.000,1433;
Packet SizePacket Size 80008000 用于与 SQL Server 的实例进行通信的网络数据包的大小(以字节为单位)。Size in bytes of the network packets used to communicate with an instance of SQL Server.

数据包大小可以大于或等于512且小于或等于32768。The packet size can be greater than or equal to 512 and less than or equal to 32768.
密码Password

- 或 --or-

PWDPWD
不可用N/A 登录 SQL Server 帐户的密码。The password for the SQL Server account logging on. 不推荐。Not recommended. 为了保持较高的安全级别,强烈建议您改用 Integrated SecurityTrusted_Connection 关键字。To maintain a high level of security, we strongly recommend that you use the Integrated Security or Trusted_Connection keyword instead. SqlCredential 是一种更安全的方式,用于指定使用 SQL Server 身份验证的连接的凭据。SqlCredential is a more secure way to specify credentials for a connection that uses SQL Server Authentication.

密码长度不能超过128个字符。The password must be 128 characters or less.
Persist Security InfoPersist Security Info

- 或 --or-

PersistSecurityInfoPersistSecurityInfo
false'false' 当设置为 falseno (强烈建议)时,如果连接处于打开状态或一直处于打开状态,则不会将安全敏感信息(如密码)作为连接的一部分返回。When set to false or no (strongly recommended), security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state. 重置连接字符串将重置所有连接字符串值(包括密码)。Resetting the connection string resets all connection string values including the password. 已识别的值为 truefalseyesnoRecognized values are true, false, yes, and no.
PoolBlockingPeriodPoolBlockingPeriod 自动Auto 设置连接池的阻塞期行为。Sets the blocking period behavior for a connection pool. 有关详细信息,请参阅 PoolBlockingPeriod 属性。See PoolBlockingPeriod property for details.
PoolingPooling 'true''true' 如果此项的值设置为 true,则在应用程序关闭时,将向池中添加任何新创建的连接。When the value of this key is set to true, any newly created connection will be added to the pool when closed by the application. 在下一次尝试打开相同的连接时,该连接将从池中提取。In a next attempt to open the same connection, that connection will be drawn from the pool.

如果连接具有相同的连接字符串,则将其视为相同。Connections are considered the same if they have the same connection string. 不同连接具有不同的连接字符串。Different connections have different connection strings.

此键的值可以为 "true"、"false"、"yes" 或 "no"。The value of this key can be "true", "false", "yes", or "no".
复制Replication false'false' true 是否支持使用连接进行复制。true if replication is supported using the connection.
事务绑定Transaction Binding Implicit UnbindImplicit Unbind 控制与登记的 System.Transactions 事务的连接关联。Controls connection association with an enlisted System.Transactions transaction.

可能的值包括:Possible values are:

Transaction Binding=Implicit Unbind;

Transaction Binding=Explicit Unbind;

隐式取消连接将导致连接在结束时与事务分离。Implicit Unbind causes the connection to detach from the transaction when it ends. 分离后,在自动模式下对连接执行其他请求。After detaching, additional requests on the connection are performed in autocommit mode. 在事务处于活动状态的情况下,执行请求时不会检查 System.Transactions.Transaction.Current 属性。The System.Transactions.Transaction.Current property is not checked when executing requests while the transaction is active. 事务结束后,会在自动提交模式下执行其他请求。After the transaction has ended, additional requests are performed in autocommit mode.

如果在最后一个命令完成之前系统结束了事务(在 using 块的作用域中),则会引发 InvalidOperationExceptionIf the system ends the transaction (in the scope of a using block) before the last command completes, it will throw InvalidOperationException.

显式取消绑定会导致连接保持附加到事务,直到连接关闭或调用显式 SqlConnection.TransactionEnlist(null)Explicit Unbind causes the connection to remain attached to the transaction until the connection is closed or an explicit SqlConnection.TransactionEnlist(null) is called. .NET Framework 4.NET Framework 4开始,对隐式取消更改会使显式解除绑定过时。Beginning in .NET Framework 4.NET Framework 4, changes to Implicit Unbind make Explicit Unbind obsolete. 如果 InvalidOperationException 不是登记事务或者登记事务未处于活动状态,则将引发 Transaction.CurrentAn InvalidOperationException is thrown if Transaction.Current is not the enlisted transaction or if the enlisted transaction is not active.
TransparentNetworkIPResolutionTransparentNetworkIPResolution 请参阅说明。See description. 将该键的值设置为 true 时,需要应用程序检索特定 DNS 条目的所有 IP 地址并尝试连接到列表中的第一个地址。When the value of this key is set to true, the application is required to retrieve all IP addresses for a particular DNS entry and attempt to connect with the first one in the list. 如果未在 0.5 秒内建立连接,应用程序将尝试并行连接到所有其他地址。If the connection is not established within 0.5 seconds, the application will try to connect to all others in parallel. 第一个地址响应后,应用程序将与响应的 IP 地址建立连接。When the first answers, the application will establish the connection with the respondent IP address.

如果 MultiSubnetFailover 项设置为 true,则将忽略 TransparentNetworkIPResolutionIf the MultiSubnetFailover key is set to true, TransparentNetworkIPResolution is ignored.

如果设置了 Failover Partner 项,TransparentNetworkIPResolution 将被忽略。If the Failover Partner key is set, TransparentNetworkIPResolution is ignored.

此项的值必须是 truefalseyesnoThe value of this key must be true, false, yes, or no.

yes 的值与 true的值相同。A value of yes is treated the same as a value of true.

no 的值与 false的值相同。A value of no is treated the same as a value of false.

默认值如下所示:The default values are as follows:

  • false 时间:false when:

    • 连接到 Azure SQL 数据库,其中的数据源结尾为:Connecting to Azure SQL Database where the data source ends with:

      • .database.chinacloudapi.cn.database.chinacloudapi.cn
      • .database.usgovcloudapi.net.database.usgovcloudapi.net
      • .database.cloudapi.de.database.cloudapi.de
      • .database.windows.net.database.windows.net
    • Authentication 为 "Active Directory Password" 或 "Active Directory 集成"Authentication is 'Active Directory Password' or 'Active Directory Integrated'
  • 在所有其他情况下,它表示 truetrue in all other cases.
TrustServerCertificateTrustServerCertificate false'false' 如果设置为 "true",则在跳过证书链以验证信任时,使用 SSL 来加密通道。When set to true, SSL is used to encrypt the channel when bypassing walking the certificate chain to validate trust. 如果将 "TrustServerCertificate" 设置为 "true",并将 "加密" 设置为 false,则不会加密该通道。If TrustServerCertificate is set to true and Encrypt is set to false, the channel is not encrypted. 已识别的值为 truefalseyesnoRecognized values are true, false, yes, and no. 有关详细信息,请参阅连接字符串语法For more information, see Connection String Syntax.
类型系统版本Type System Version 不可用N/A 一个字符串值,该值指示应用程序所需的类型系统。A string value that indicates the type system the application expects. 可用于客户端应用程序的功能取决于 SQL Server 版本和数据库的兼容性级别。The functionality available to a client application is dependent on the version of SQL Server and the compatibility level of the database. 如果使用的是 SQL Server 的其他版本,则显式设置编写的客户端应用程序所针对的类型系统版本可避免导致应用程序中断的潜在问题。Explicitly setting the type system version that the client application was written for avoids potential problems that could cause an application to break if a different version of SQL Server is used. 注意: 无法为在 SQL Server 中在进程内执行的公共语言运行时(CLR)代码设置类型系统版本。Note: The type system version cannot be set for common language runtime (CLR) code executing in-process in SQL Server. 有关详细信息,请参阅SQL Server 公共语言运行时集成For more information, see SQL Server Common Language Runtime Integration.

可能的值包括:Possible values are:

Type System Version=SQL Server 2012;

Type System Version=SQL Server 2008;

Type System Version=SQL Server 2005;

Type System Version=Latest;

Type System Version=SQL Server 2012; 指定应用程序将需要11.0.0.0 版本的。Type System Version=SQL Server 2012; specifies that the application will require version 11.0.0.0 of Microsoft.SqlServer.Types.dll. 其他 Type System Version 设置将需要的版本10.0.0.0。The other Type System Version settings will require version 10.0.0.0 of Microsoft.SqlServer.Types.dll.

Latest 已过时,不应使用。Latest is obsolete and should not be used. Latest 等效于 Type System Version=SQL Server 2008;Latest is equivalent to Type System Version=SQL Server 2008;.
User IDUser ID

- 或 --or-

UIDUID

- 或 --or-
不可用N/A SQL Server 的登录帐户。The SQL Server login account. 不推荐。Not recommended. 为了保持较高的安全级别,强烈建议您改用 Integrated SecurityTrusted_Connection 关键字。To maintain a high level of security, we strongly recommend that you use the Integrated Security or Trusted_Connection keywords instead. SqlCredential 是一种更安全的方式,用于指定使用 SQL Server 身份验证的连接的凭据。SqlCredential is a more secure way to specify credentials for a connection that uses SQL Server Authentication.

用户 ID 不得超过128个字符。The user ID must be 128 characters or less.
User InstanceUser Instance false'false' 一个值,该值指示是否将连接从默认 SQL Server Express 实例重定向到在调用方帐户下运行的运行时启动的实例。A value that indicates whether to redirect the connection from the default SQL Server Express instance to a runtime-initiated instance running under the account of the caller.
Workstation IDWorkstation ID

- 或 --or-

WSIDWSID
本地计算机名称The local computer name 连接到 SQL Server 的工作站的名称。The name of the workstation connecting to SQL Server.

ID 不得超过128个字符。The ID must be 128 characters or less.

下面的列表包含 ConnectionString中连接池值的有效名称。The following list contains the valid names for connection pooling values within the ConnectionString. 有关详细信息,请参阅 SQL Server 连接池 (ADO.NET)For more information, see SQL Server Connection Pooling (ADO.NET).

  • 连接生存期(或负载平衡超时)Connection Lifetime (or Load Balance Timeout)

  • 登记Enlist

  • 最大池大小Max Pool Size

  • Min Pool SizeMin Pool Size

  • PoolingPooling

在设置需要布尔值的关键字或连接池值时,可以使用 "是" 而不是 "true" 和 "no" 而不是 "false"。When you are setting keyword or connection pooling values that require a Boolean value, you can use 'yes' instead of 'true', and 'no' instead of 'false'. 整数值表示为字符串。Integer values are represented as strings.

Note

SQL Server 的 .NET Framework 数据提供程序使用自己的协议与 SQL Server 进行通信。The .NET Framework Data Provider for SQL Server uses its own protocol to communicate with SQL Server. 因此,在连接到 SQL Server 时,它不支持使用 ODBC 数据源名称(DSN),因为它不会添加 ODBC 层。Therefore, it does not support the use of an ODBC data source name (DSN) when connecting to SQL Server because it does not add an ODBC layer.

Note

SQL Server 的 .NET Framework 数据提供程序不支持通用数据链接(UDL)文件。Universal data link (UDL) files are not supported for the .NET Framework Data Provider for SQL Server.

Caution

在此版本中,应用程序在构造基于用户输入的连接字符串时应小心(例如,从对话框检索用户 ID 和密码信息,并将其附加到连接字符串)。In this release, the application 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). 如果需要基于用户输入构造连接字符串,请使用新的 SqlConnectionStringBuilder,它将验证连接字符串并帮助消除此问题。If you need to construct connection strings based on user input, use the new SqlConnectionStringBuilder, which validates the connection string and helps to eliminate this problem. 有关详细信息,请参阅连接字符串生成器See Connection String Builders for more information.

Applies to

See also