SqlConnection.ConnectionString SqlConnection.ConnectionString SqlConnection.ConnectionString SqlConnection.ConnectionString Property


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

 virtual property System::String ^ ConnectionString { System::String ^ get(); void set(System::String ^ value); };
public override string ConnectionString { get; set; }
member this.ConnectionString : string with get, set
Public Overrides Property ConnectionString As 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.



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


下面的示例创建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;


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

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


        Console.WriteLine("State: {0}", connection.State)
        Console.WriteLine("ConnectionString: {0}", _
    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


ConnectionString类似于的 OLE DB 连接字符串,但并不完全相同。The ConnectionString is similar to an OLE DB connection string, but is not identical. 不同于 OLE DB 或 ADO,则返回的连接字符串是与用户设置相同ConnectionString,如果 Persist Security Info 值设置为安全信息减去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 属性返回中包含的那些设置ConnectionStringSqlConnection 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. 例如,如果设置包含的连接字符串"数据库 = AdventureWorks",然后重置的连接字符串"数据源 = 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. 如果在分析时,运行时异常,如发现语法错误ArgumentException,生成。If 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. 而不使用分隔符,可能的连接字符串中使用单引号或双引号括起来 (例如,数据源 = 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.

下表列出了中的关键字值的有效名称ConnectionStringThe 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 NameApplication Name 不可用N/A 应用程序或.NET SQLClient 数据提供程序如果未不提供任何应用程序名称的名称。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:


有关对 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-

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.

- 或 --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. AttachDBFilename 只能用于扩展名为.mdf 的主数据文件。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 用于身份验证方法连接到 SQL 数据库使用 Azure Active Directory 身份验证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-

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-

不可用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-


- 或 --or-


- 或 --or-


- 或 --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:


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

数据源必须使用 TCP 格式或 Named Pipes 格式。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.

Named Pipes 格式如下所示: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 的使用而不是共享内存,或者由前缀tcp: 到在连接字符串,或使用的服务器名称localhostNote: 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.
EncryptEncrypt 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,连接字符串中指定的服务器名称 (或 IP 地址),SQL Server SSL 证书中的服务器名称 (或 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.
EnlistEnlist '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.

如果此密钥的值为"",然后Initial Catalog必须存在,且其值不能""。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-

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

数据库名称可以是 128 个字符或更少。The database name can be 128 characters or less.
Integrated SecurityIntegrated Security

- 或 --or-

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.

可识别的值为truefalseyesno,并sspi(强烈推荐),这等同于trueRecognized 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 SizeMax 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 始终指定multiSubnetFailover=True连接到可用性组侦听器的 SQL Server 2012 (或更高版本) 可用性组或 SQL Server 2012 (或更高版本) 故障转移群集实例时。Always 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:


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

- 或 --or-


- 或 --or-

不可用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 (VIA)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=,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.

- 或 --or-

不可用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-

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"否"。The value of this key can be "true", "false", "yes", or "no".
ReplicationReplication 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.

如果系统结束事务 (使用的范围内的块) 的最后一个命令完成之前,它会引发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键设置为trueTransparentNetworkIPResolution将被忽略。If the MultiSubnetFailover key is set to true, TransparentNetworkIPResolution is ignored.

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

此键的值必须是truefalseyes,或noThe value of this key must be true, false, yes, or no.

值为yes是处理相同的值作为trueA value of yes is treated the same as a value of true.

值为no是处理相同的值作为falseA 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 密码或 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; 指定应用程序将需要版本 的 Microsoft.SqlServer.Types.dll。Type System Version=SQL Server 2012; specifies that the application will require version of Microsoft.SqlServer.Types.dll. 其他Type System Version设置将需要版本 的 Microsoft.SqlServer.Types.dll。The other Type System Version settings will require version of Microsoft.SqlServer.Types.dll.

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

- 或 --or-


- 或 --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-

本地计算机名称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.

以下列表包含连接池内的值的有效名称ConnectionStringThe 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)

  • EnlistEnlist

  • Max Pool SizeMax Pool Size

  • Min Pool SizeMin Pool Size

  • PoolingPooling

当您在设置关键字或连接池需要一个布尔值的值时,可以是使用而不是 'true',和否而不是 '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.


SQL Server 的.NET Framework 数据提供程序使用其自己的协议来与 SQL Server 通信。The .NET Framework Data Provider for SQL Server uses its own protocol to communicate with SQL Server. 因此,它不支持使用 ODBC 数据源名称 (DSN) 的连接到 SQL Server,因为它不会添加一个 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.


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


在此版本中,应用程序时应小心构造基于用户输入 (例如,从一个对话框,并将其追加到连接字符串检索用户 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.