System.Data.SqlClient 4.1.0.0 4.4.0.0 4.5.0.0 4.6.0.0 4.6.1.0 4.6.1.1 4.6.1.5 4.6.1.6 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 System.Data.Common.DbConnection System.ComponentModel.Component System.Data.IDbConnection System.ICloneable System.IDisposable [System.ComponentModel.DefaultEvent("InfoMessage")] [<System.ComponentModel.DefaultEvent("InfoMessage")>] Represents a connection to a SQL Server database. This class cannot be inherited. object represents a unique session to a SQL Server data source. With a client/server database system, it is equivalent to a network connection to the server. is used together with and to increase performance when connecting to a Microsoft SQL Server database. For all third-party SQL Server products and other OLE DB-supported data sources, use . When you create an instance of , all properties are set to their initial values. For a list of these values, see the constructor. See for a list of the keywords in a connection string. If the goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling `Close` or `Dispose`. `Close` and `Dispose` are functionally equivalent. If the connection pooling value `Pooling` is set to `true` or `yes`, the underlying connection is returned back to the connection pool. On the other hand, if `Pooling` is set to `false` or `no`, the underlying connection to the server is actually closed. > [!NOTE] > Login and logout events will not be raised on the server when a connection is fetched from or returned to the connection pool, because the connection is not actually closed when it is returned to the connection pool. For more information, see [SQL Server Connection Pooling (ADO.NET)](/dotnet/framework/data/adonet/sql-server-connection-pooling). To ensure that connections are always closed, open the connection inside of a `using` block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block. ```vb Using connection As New SqlConnection(connectionString) connection.Open() ' Do work here; connection closed on following line. End Using ``` ```csharp using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // Do work here; connection closed on following line. } ``` > [!NOTE] > To deploy high-performance applications, you must use connection pooling. When you use the .NET Framework Data Provider for SQL Server, you do not have to enable connection pooling because the provider manages this automatically, although you can modify some settings. For more information, see [SQL Server Connection Pooling (ADO.NET)](/dotnet/framework/data/adonet/sql-server-connection-pooling). If a is generated by the method executing a , the remains open when the severity level is 19 or less. When the severity level is 20 or greater, the server ordinarily closes the . However, the user can reopen the connection and continue. An application that creates an instance of the object can require all direct and indirect callers to have sufficient permission to the code by setting declarative or imperative security demands. makes security demands using the object. Users can verify that their code has sufficient permissions by using the object. Users and administrators can also use the [Caspol.exe (Code Access Security Policy Tool)](/dotnet/framework/tools/caspol-exe-code-access-security-policy-tool) to modify security policy at the machine, user, and enterprise levels. For more information, see [Security in .NET](/dotnet/standard/security/). For an example demonstrating how to use security demands, see [Code Access Security and ADO.NET](/dotnet/framework/data/adonet/code-access-security). For more information about handling warning and informational messages from the server, see [Connection Events](/dotnet/framework/data/adonet/connection-events). For more information about SQL Server engine errors and error messages, see [Database Engine Events and Errors](/sql/relational-databases/errors-events/database-engine-events-and-errors). > [!CAUTION] > You can force TCP instead of shared memory. You can do that by prefixing tcp: to the server name in the connection string or you can use localhost. ## Examples The following example creates a and a . The is opened and set as the for the . The example then calls . To accomplish this, the is passed a SqlConnection and a query string that is a Transact-SQL INSERT statement. The connection is closed automatically when the code exits the using block. :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlCommand.ExecuteNonQuery Example/CS/source.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Data.SqlClient/SqlCommand/ExecuteNonQuery/source.vb" id="Snippet1"::: ]]> Connecting to a Data Source in ADO.NET SQL Server and ADO.NET ADO.NET Overview System.Data.SqlClient 4.1.0.0 Initializes a new instance of the class. ADO.NET Overview Constructor System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 Initializes a new instance of the class. is created, the read/write properties are set to the following initial values unless they are specifically set using their associated keywords in the property. |Properties|Initial value| |----------------|-------------------| ||empty string ("")| ||15| ||empty string ("")| ||empty string ("")| You can change the value for these properties only by using the property. The class provides functionality for creating and managing the contents of connection strings. ## Examples The following example creates and opens a . :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlConnection.SqlConnection Example/CS/source.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Data.SqlClient/SqlConnection/.ctor/source.vb" id="Snippet1"::: ]]> Connecting to a Data Source in ADO.NET SQL Server and ADO.NET ADO.NET Overview Constructor System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 The connection used to open the SQL Server database. Initializes a new instance of the class when given a string that contains the connection string. is created, the read/write properties are set to the following initial values unless they are specifically set using their associated keywords in the property. |Properties|Initial value| |----------------|-------------------| || `connectionString` | ||15| ||empty string ("")| ||empty string ("")| You can change the value for these properties only by using the property. The class provides functionality for creating and managing the contents of connection strings. ## Examples The following example creates and opens a . :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlConnection.SqlConnection1 Example/CS/source.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Data.SqlClient/SqlConnection/.ctor/source1.vb" id="Snippet1"::: ]]> The supplied connection string argument failed validation. Connecting to a Data Source (ADO.NET) Using the .NET Framework Data Provider for SQL Server ADO.NET Overview Constructor System.Data 4.0.0.0 System.Data.SqlClient 4.6.1.6 A connection string that does not use any of the following connection string keywords: , , or ; or that does not use . A object. If is null, is functionally equivalent to . Initializes a new instance of the class given a connection string, that does not use and a object that contains the user ID and password. To be added. The supplied connection string argument failed validation. ADO.NET Overview Property System.Data 4.0.0.0 System.Data.SqlClient 4.6.1.6 [System.ComponentModel.Browsable(false)] [<System.ComponentModel.Browsable(false)>] [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [<System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)>] System.String Gets or sets the access token for the connection. The access token for the connection. To be added. Method System.Data.SqlClient 4.1.0.0 System.Data 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 System.Data.Common.DbTransaction To be added. To be added. To be added. To be added. System.Data.SqlClient 4.1.0.0 Starts a database transaction. ADO.NET Overview Method System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 System.Data.SqlClient.SqlTransaction Starts a database transaction. An object representing the new transaction. or method. To make sure that the .NET Framework Data Provider for SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server. > [!NOTE] > If you do not specify an isolation level, the default isolation level is used. To specify an isolation level with the method, use the overload that takes the `iso` parameter (). The isolation level set for a transaction persists after the transaction is completed and until the connection is closed or disposed. Setting the isolation level to **Snapshot** in a database where the snapshot isolation level is not enabled does not throw an exception. The transaction will complete using the default isolation level. > [!CAUTION] > If a transaction is started and a level 16 or higher error occurs on the server, the transaction will not be rolled back until the method is invoked. No exception is thrown on **ExecuteReader**. > [!CAUTION] > When your query returns a large amount of data and calls `BeginTransaction`, a is thrown because SQL Server does not allow parallel transactions when using MARS. To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open. For more information on SQL Server transactions, see [Transactions (Transact-SQL)](/sql/t-sql/language-elements/transactions-transact-sql). ## Examples The following example creates a and a . It also demonstrates how to use the , a , and methods. :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlConnection.BeginTransaction Example/CS/source.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Data/IDbTransaction/Overview/source.vb" id="Snippet1"::: ]]> Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). Parallel transactions are not supported. Transactions and Concurrency Connecting to a Data Source in ADO.NET SQL Server and ADO.NET ADO.NET Overview Method System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 System.Data.SqlClient.SqlTransaction The isolation level under which the transaction should run. Starts a database transaction with the specified isolation level. An object representing the new transaction. or method. To make sure that the .NET Framework Data Provider for SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server. > [!NOTE] > After a transaction is committed or rolled back, the isolation level of the transaction persists for all subsequent commands that are in autocommit mode (the SQL Server default). This can produce unexpected results, such as an isolation level of REPEATABLE READ persisting and locking other users out of a row. To reset the isolation level to the default (READ COMMITTED), execute the Transact-SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED statement, or call followed immediately by . For more information on SQL Server isolation levels, see [Transaction Isolation Levels](/sql/t-sql/language-elements/transaction-isolation-levels). For more information on SQL Server transactions, see [Transactions (Transact-SQL)](/sql/t-sql/language-elements/transactions-transact-sql). > [!CAUTION] > When your query returns a large amount of data and calls `BeginTransaction`, a is thrown because SQL Server does not allow parallel transactions when using MARS. To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open. ## Examples The following example creates a and a . It also demonstrates how to use the , a , and methods. :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlConnection.BeginTransaction1 Example/CS/source.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Data.SqlClient/SqlConnection/BeginTransaction/source.vb" id="Snippet1"::: ]]> Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). Parallel transactions are not supported. Transactions (ADO.NET) Connecting to a Data Source (ADO.NET) Using the .NET Framework Data Provider for SQL Server ADO.NET Overview Method System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 System.Data.SqlClient.SqlTransaction The name of the transaction. Starts a database transaction with the specified transaction name. An object representing the new transaction. and in the `savePoint` parameter of the method. You must explicitly commit or roll back the transaction using the or method. To make sure that the .NET Framework Data Provider for SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server. For more information on SQL Server transactions, see [Transactions (Transact-SQL)](/sql/t-sql/language-elements/transactions-transact-sql). > [!CAUTION] > When your query returns a large amount of data and calls `BeginTransaction`, a is thrown because SQL Server does not allow parallel transactions when using MARS. To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open. ## Examples The following example creates a and a . It also demonstrates how to use the , a , and methods. :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlConnection.BeginTransaction2 Example/CS/source.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Data.SqlClient/SqlConnection/BeginTransaction/source1.vb" id="Snippet1"::: ]]> Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). Parallel transactions are not supported. Transactions (ADO.NET) Connecting to a Data Source (ADO.NET) Using the .NET Framework Data Provider for SQL Server ADO.NET Overview Method System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 System.Data.SqlClient.SqlTransaction The isolation level under which the transaction should run. The name of the transaction. Starts a database transaction with the specified isolation level and transaction name. An object representing the new transaction. and in the `savePoint` parameter of the method. You must explicitly commit or roll back the transaction using the or method. To make sure that the SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server. > [!NOTE] > After a transaction is committed or rolled back, the isolation level of the transaction persists for all subsequent commands that are in autocommit mode (the SQL Server default). This can produce unexpected results, such as an isolation level of REPEATABLE READ persisting and locking other users out of a row. To reset the isolation level to the default (READ COMMITTED), execute the Transact-SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED statement, or call followed immediately by . For more information on SQL Server isolation levels, see [Transaction Isolation Levels](/sql/t-sql/language-elements/transaction-isolation-levels). For more information on SQL Server transactions, see [Transactions (Transact-SQL)](/sql/t-sql/language-elements/transactions-transact-sql). > [!CAUTION] > When your query returns a large amount of data and calls `BeginTransaction`, a is thrown because SQL Server does not allow parallel transactions when using MARS. To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open. ## Examples The following example creates a and a . It also demonstrates how to use the , a , and methods. :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlConnection.BeginTransaction3 Example/CS/source.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Data.SqlClient/SqlConnection/BeginTransaction/source2.vb" id="Snippet1"::: ]]> Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). Parallel transactions are not supported. Transactions (ADO.NET) Connecting to a Data Source (ADO.NET) Using the .NET Framework Data Provider for SQL Server ADO.NET Overview Method M:System.Data.IDbConnection.ChangeDatabase(System.String) System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 System.Void The name of the database to use instead of the current database. Changes the current database for an open . and displays some of its read-only properties. :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlConnection.Database Example/CS/source.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Data.SqlClient/SqlConnection/ChangeDatabase/source.vb" id="Snippet1"::: ]]> The database name is not valid. The connection is not open. Cannot change the database. Connecting to a Data Source in ADO.NET SQL Server and ADO.NET ADO.NET Overview System.Data 2.0.5.0 4.0.0.0 Changes the SQL Server password. ADO.NET Overview Method System.Data 2.0.0.0 4.0.0.0 System.Data.SqlClient 4.6.1.6 System.Void The connection string that contains enough information to connect to the server that you want. The connection string must contain the user ID and the current password. The new password to set. This password must comply with any password security policy set on the server, including minimum length, requirements for specific characters, and so on. Changes the SQL Server password for the user indicated in the connection string to the specified new password. method changes the SQL Server password for the user indicated in the supplied `connectionString` parameter to the value supplied in the `newPassword` parameter. If the connection string includes the option for integrated security (that is, "Integrated Security=True" or the equivalent), an exception is thrown. To determine that the password has expired, calling the method raises a . In order to indicate that the password that is contained within the connection string must be reset, the property for the exception contains the status value 18487 or 18488. The first value (18487) indicates that the password has expired and the second (18488) indicates that the password must be reset before logging in. This method opens its own connection to the server, requests the password change, and closes the connection as soon as it has completed. This connection is not retrieved from or returned to the SQL Server connection pool. ]]> The connection string includes the option to use integrated security. Or The exceeds 128 characters. Either the or the parameter is null. Connection Strings (ADO.NET) Connecting to a Data Source (ADO.NET) Using the .NET Framework Data Provider for SQL Server ADO.NET Overview Method System.Data 4.0.0.0 System.Data.SqlClient 4.6.1.6 System.Void The connection string that contains enough information to connect to a server. The connection string should not use any of the following connection string keywords: , , or ; or . A object. The new password. must be read only. The password must also comply with any password security policy set on the server (for example, minimum length and requirements for specific characters). The new password. must be read only. The password must also comply with any password security policy set on the server (for example, minimum length and requirements for specific characters). Changes the SQL Server password for the user indicated in the object. To be added. The connection string contains any combination of , , or . -or- The connection string contains . -or- (or ) is greater than 128 characters. -or- (or ) is not read only. -or- (or ) is an empty string. One of the parameters (, , or ) is null. ADO.NET Overview Method System.Data.SqlClient 4.1.0.0 System.Data 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 System.Void Empties the connection pool. resets (or empties) the connection pool. If there are connections in use at the time of the call, they are marked appropriately and will be discarded (instead of being returned to the pool) when is called on them. ]]> SQL Server Connection Pooling (ADO.NET) ADO.NET Overview Method System.Data.SqlClient 4.1.0.0 System.Data 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 System.Void The to be cleared from the pool. Empties the connection pool associated with the specified connection. clears the connection pool that is associated with the `connection`. If additional connections associated with `connection` are in use at the time of the call, they are marked appropriately and are discarded (instead of being returned to the pool) when is called on them. ]]> SQL Server Connection Pooling (ADO.NET) ADO.NET Overview Property System.Data.SqlClient 4.1.0.0 System.Data 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [<System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)>] System.Guid The connection ID of the most recent connection attempt, regardless of whether the attempt succeeded or failed. The connection ID of the most recent connection attempt. works regardless of which version of the server you connect to, but extended events logs and entry on connectivity ring buffer errors will not be present in SQL Server 2008 R2 and earlier. You can locate the connection ID in the extended events log to see if the failure was on the server if the extended event for logging connection ID is enabled. You can also locate the connection ID in the connection ring buffer for certain connection errors. If the connection ID is not in the connection ring buffer, you can assume a network error. ]]> ADO.NET Overview Method M:System.Data.IDbConnection.Close System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 System.Void Closes the connection to the database. This is the preferred method of closing any open connection. method rolls back any pending transactions. It then releases the connection to the connection pool, or closes the connection if connection pooling is disabled. > [!NOTE] > Pending transactions started using Transact-SQL or are automatically rolled back when the connection is reset if connection pooling is enabled. If connection pooling is off, the transaction is rolled back after `SqlConnection.Close` is called. Transactions started through are controlled through the `System.Transactions` infrastructure, and are not affected by `SqlConnection.Close`. An application can call more than one time. No exception is generated. If the goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling `Close` or `Dispose`. `Close` and `Dispose` are functionally equivalent. If the connection pooling value `Pooling` is set to `true` or `yes`, the underlying connection is returned back to the connection pool. On the other hand, if `Pooling` is set to `false` or `no`, the underlying connection to the server is closed. > [!NOTE] > Login and logout events will not be raised on the server when a connection is fetched from or returned to the connection pool, because the connection is not actually closed when it is returned to the connection pool. For more information, see [SQL Server Connection Pooling (ADO.NET)](/dotnet/framework/data/adonet/sql-server-connection-pooling). > [!CAUTION] > Do not call `Close` or `Dispose` on a Connection, a DataReader, or any other managed object in the `Finalize` method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a `Finalize` method in your class definition. For more information, see [Garbage Collection](/dotnet/standard/garbage-collection/). ## Examples The following example creates a , opens it, displays some of its properties. The connection is automatically closed at the end of the `using` block. :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlConnection.Open Example/CS/source.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Data.SqlClient/SqlConnection/Close/source.vb" id="Snippet1"::: ]]> The connection-level error that occurred while opening the connection. SQL Server Connection Pooling (ADO.NET) Connecting to a Data Source in ADO.NET SQL Server and ADO.NET ADO.NET Overview Property System.Data 4.0.0.0 System.Data.SqlClient [System.ComponentModel.DefaultValue(null)] [<System.ComponentModel.DefaultValue(null)>] System.TimeSpan Gets or sets the time-to-live for column encryption key entries in the column encryption key cache for the Always Encrypted feature. The default value is 2 hours. 0 means no caching at all. The time interval. To be added. Property System.Data 4.0.0.0 System.Data.SqlClient [System.ComponentModel.DefaultValue(null)] [<System.ComponentModel.DefaultValue(null)>] System.Boolean Gets or sets a value that indicates whether query metadata caching is enabled (true) or not (false) for parameterized queries running against Always Encrypted enabled databases. The default value is true. Returns true if query metadata caching is enabled; otherwise false. true is the default. Property System.Data 4.0.0.0 System.Data.SqlClient [System.ComponentModel.DefaultValue(null)] [<System.ComponentModel.DefaultValue(null)>] System.Collections.Generic.IDictionary<System.String,System.Collections.Generic.IList<System.String>> Allows you to set a list of trusted key paths for a database server. If while processing an application query the driver receives a key path that is not on the list, the query will fail. This property provides additional protection against security attacks that involve a compromised SQL Server providing fake key paths, which may lead to leaking key store credentials. The list of trusted master key paths for the column encryption. To be added. Property P:System.Data.IDbConnection.ConnectionString System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 [System.ComponentModel.DefaultValue("")] [<System.ComponentModel.DefaultValue("")>] [System.ComponentModel.Editor("Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, Microsoft.VSDesigner, Version=7.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(System.Drawing.Design.UITypeEditor))] [<System.ComponentModel.Editor("Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, Microsoft.VSDesigner, Version=7.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(System.Drawing.Design.UITypeEditor))>] [System.ComponentModel.RecommendedAsConfigurable(true)] [<System.ComponentModel.RecommendedAsConfigurable(true)>] [System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.All)] [<System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.All)>] [System.Data.DataSysDescription("SqlConnection_ConnectionString")] [<System.Data.DataSysDescription("SqlConnection_ConnectionString")>] [System.ComponentModel.Editor("Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, Microsoft.VSDesigner, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [<System.ComponentModel.Editor("Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, Microsoft.VSDesigner, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")>] [System.ComponentModel.Editor("Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [<System.ComponentModel.Editor("Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")>] [System.ComponentModel.SettingsBindable(true)] [<System.ComponentModel.SettingsBindable(true)>] System.String Gets or sets the string used to open a SQL Server database. 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. is similar to an OLE DB connection string, but is not identical. Unlike OLE DB or ADO, the connection string that is returned is the same as the user-set , minus security information if the Persist Security Info value is set to `false` (default). The .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`. You can use the property to connect to a database. The following example illustrates a typical connection string. ```txt "Persist Security Info=False;Integrated Security=true;Initial Catalog=Northwind;server=(local)" ``` Use the new to construct valid connection strings at run time. For more information, see [Connection String Builders](/dotnet/framework/data/adonet/connection-string-builders). The 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. properties return only those settings that are contained in the . 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. Resetting the on a closed connection resets all connection string values (and related properties) including the password. 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 property is no longer set to "AdventureWorks". The connection string is parsed immediately after being set. If errors in syntax are found when parsing, a runtime exception, such as , 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. 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. The following table lists the valid names for keyword values within the . | Keyword | Default | Description | |--------------------|---------|----------------------------------| | `Addr` | N/A | Synonym of **Data Source**. | | `Address` | N/A | Synonym of **Data Source**. | | `App` | N/A | Synonym of **Application Name**. | | `Application Name` | N/A | The name of the application, or '.NET SQLClient Data Provider' if no application name is provided.

An application name can be 128 characters or less. | | `ApplicationIntent` | `ReadWrite` |Declares the application workload type when connecting to a server. Possible values are `ReadOnly` and `ReadWrite`. For example:

`ApplicationIntent=ReadOnly`

For more information about SqlClient support for Always On Availability Groups, see [SqlClient Support for High Availability, Disaster Recovery](/dotnet/framework/data/adonet/sql/sqlclient-support-for-high-availability-disaster-recovery).| | `Asynchronous Processing`
-or-
`Async` |'false'|When `true`, enables asynchronous operation support. Recognized values are `true`, `false`, `yes`, and `no`.

This property is ignored beginning in .NET Framework 4.5. For more information about SqlClient support for asynchronous programming, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming).| | `AttachDBFilename`
-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 is only supported for primary data files with an .mdf extension.

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.

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.

The path may be absolute or relative by using the DataDirectory substitution string. If DataDirectory is used, the database file must exist within a subdirectory of the directory pointed to by the substitution string. **Note:** Remote server, HTTP, and UNC path names are not supported.

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"`

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|The authentication method used for [Connecting to SQL Database By Using Azure Active Directory Authentication](/azure/azure-sql/database/authentication-aad-overview#connect-by-using-azure-ad-identities).

Valid values are:

Active Directory Integrated, Active Directory Password, Sql Password.| | `Column Encryption Setting` |N/A|Enables or disables [Always Encrypted](/sql/relational-databases/security/encryption/always-encrypted-database-engine?view=sql-server-2017) functionality for the connection.| | `Connect Timeout`
-or-
`Connection Timeout`
-or-
`Timeout` |15|The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.

Valid values are greater than or equal to 0 and less than or equal to 2147483647.

When opening a connection to a Azure SQL Database, set the connection timeout to 30 seconds.| | `Connection Lifetime`
-or-
`Load Balance Timeout` |0|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.

A value of zero (0) causes pooled connections to have the maximum connection timeout.| | `ConnectRetryCount` |1|Controls the number of reconnection attempts after the client identifies an idle connection failure. Valid values are 0 to 255. The default is 1. 0 means do not attempt to reconnect (disable connection resiliency).

For additional information about connection resiliency, see [.NET SqlConnection parameters for connection retry](/azure/azure-sql/database/troubleshoot-common-connectivity-issues?view=azuresql#net-sqlconnection-parameters-for-connection-retry) and [Technical Article - Idle Connection Resiliency](https://download.microsoft.com/download/D/2/0/D20E1C5F-72EA-4505-9F26-FEF9550EFD44/Idle%20Connection%20Resiliency.docx).| | `ConnectRetryInterval` |10|Specifies the time between each connection retry attempt (ConnectRetryCount). Valid values are 1 to 60 seconds (default=10), applied after the first reconnection attempt. 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. 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 connection resiliency, see [.NET SqlConnection parameters for connection retry](/azure/azure-sql/database/troubleshoot-common-connectivity-issues?view=azuresql#net-sqlconnection-parameters-for-connection-retry) and [Technical Article - Idle Connection Resiliency](https://download.microsoft.com/download/D/2/0/D20E1C5F-72EA-4505-9F26-FEF9550EFD44/Idle%20Connection%20Resiliency.docx).| | `Context Connection` |'false'| `true` if an in-process connection to SQL Server should be made.| | `Current Language`
-or-
`Language` |N/A|Sets the language used for database server warning or error messages.

The language name can be 128 characters or less.| | `Data Source`
-or-
`Server`
-or-
`Address`
-or-
`Addr`
-or-
`Network Address` |N/A|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`

When specifying a local instance, always use (local). To force a protocol, add one of the following prefixes:

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

Beginning in .NET Framework 4.5, you can also connect to a LocalDB database as follows:

`server=(localdb)\\myInstance`

For more information about LocalDB, see [SqlClient Support for LocalDB](/dotnet/framework/data/adonet/sql/sqlclient-support-for-localdb).

**Data Source** must use the TCP format or the Named Pipes format.

TCP format is as follows:

- 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. This format is not applicable when connecting to Azure SQL Database. 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
- IPv4Address
- IPv6Address

The instance name is used to resolve to a particular TCP/IP port number on which a database instance is hosted. 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\\

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
- IPv4Address
- IPv6Address

The pipe name is used to identify the database instance to which the .NET Framework application will be connected.

If the value of the **Network** key is specified, the prefixes "tcp:" and "np:" should not be specified. **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'|When `true`, SQL Server uses SSL encryption for all data sent between the client and server if the server has a certificate installed. Recognized values are `true`, `false`, `yes`, and `no`. For more information, see [Connection String Syntax](/dotnet/framework/data/adonet/connection-string-syntax).

Beginning in .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.| | `Enlist` |'true'| `true` indicates that the SQL Server connection pooler automatically enlists the connection in the creation thread's current transaction context.| | `Failover 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 "".

The server name can be 128 characters or less.

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.

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 Catalog`
-or-
`Database` |N/A|The name of the database.

The database name can be 128 characters or less.| | `Integrated Security`
-or-
`Trusted_Connection` |'false'|When `false`, User ID and Password are specified in the connection. When `true`, the current Windows account credentials are used for authentication.

Recognized values are `true`, `false`, `yes`, `no`, and `sspi` (strongly recommended), which is equivalent to `true`.

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.

is a more secure way to specify credentials for a connection that uses SQL Server Authentication (`Integrated Security=false`).| | `Max Pool Size` |100|The maximum number of connections that are allowed in the pool.

Valid values are greater than or equal to 1. Values that are less than **Min Pool Size** generate an error.| | `Min Pool Size` |0|The minimum number of connections that are allowed in the pool.

Valid values are greater than or equal to 0. Zero (0) in this field means no minimum connections are initially opened.

Values that are greater than **Max Pool Size** generate an error.| | `MultipleActiveResultSets` |'false'|When `true`, an application can maintain multiple active result sets (MARS). When `false`, an application must process or cancel all result sets from one batch before it can execute any other batch on that connection.

Recognized values are `true` and `false`.

For more information, see [Multiple Active Result Sets (MARS)](/dotnet/framework/data/adonet/sql/multiple-active-result-sets-mars).| | `MultiSubnetFailover` |FALSE|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` configures SqlClient to provide faster detection of and connection to the (currently) active server. Possible values are `Yes` and `No`, `True` and `False` or `1` and `0`. For example:

`MultiSubnetFailover=True`

The default is `False`. For more information about SqlClient's support for Always On AGs, see [SqlClient Support for High Availability, Disaster Recovery](/dotnet/framework/data/adonet/sql/sqlclient-support-for-high-availability-disaster-recovery).| | `Network Library`
-or-
`Network`
-or-
`Net` |N/A|The network library used to establish a connection to an instance of SQL Server. Supported values include:

dbnmpntw (Named Pipes)

dbmsrpcn (Multiprotocol, Windows RPC)

dbmsadsn (Apple Talk)

dbmsgnet (VIA)

dbmslpcn (Shared Memory)

dbmsspxn (IPX/SPX)

dbmssocn (TCP/IP)

Dbmsvinn (Banyan Vines)

The corresponding network DLL must be installed on the system to which you connect. If you do not specify a network and you use a local server (for example, "." or "(local)"), shared memory is used. 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 Size` |8000|Size in bytes of the network packets used to communicate with an instance of SQL Server.

The packet size can be greater than or equal to 512 and less than or equal to 32768.| | `Password`
-or-
`PWD` |N/A|The password for the SQL Server account logging on. Not recommended. To maintain a high level of security, we strongly recommend that you use the `Integrated Security` or `Trusted_Connection` keyword instead. is a more secure way to specify credentials for a connection that uses SQL Server Authentication.

The password must be 128 characters or less.| | `Persist Security Info`
-or-
`PersistSecurityInfo` |'false'|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. Recognized values are `true`, `false`, `yes`, and `no`.| | `PoolBlockingPeriod` |Auto|Sets the blocking period behavior for a connection pool. See property for details.| | `Pooling` |'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.

The value of this key can be "true", "false", "yes", or "no".| | `Replication` |'false'| `true` if replication is supported using the connection.| | `Transaction Binding` |Implicit Unbind|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. 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.

If the system ends the transaction (in the scope of a using block) before the last command completes, it will throw .

Explicit Unbind causes the connection to remain attached to the transaction until the connection is closed or an explicit `SqlConnection.TransactionEnlist(null)` is called. Beginning in .NET Framework 4, changes to Implicit Unbind make Explicit Unbind obsolete. An `InvalidOperationException` is thrown if `Transaction.Current` is not the enlisted transaction or if the enlisted transaction is not active.| | `TransparentNetworkIPResolution` |See description.|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. If the connection is not established within 0.5 seconds, the application will try to connect to all others in parallel. When the first answers, the application will establish the connection with the respondent IP address.

If the `MultiSubnetFailover` key is set to `true`, `TransparentNetworkIPResolution` is ignored.

If the `Failover Partner` key is set, `TransparentNetworkIPResolution` is ignored.

The value of this key must be `true`, `false`, `yes`, or `no`.

A value of `yes` is treated the same as a value of `true`.

A value of `no` is treated the same as a value of `false`.

The default values are as follows:

  • `false` when:

    • Connecting to Azure SQL Database where the data source ends with:

      • .database.chinacloudapi.cn
      • .database.usgovcloudapi.net
      • .database.cloudapi.de
      • .database.windows.net
    • `Authentication` is 'Active Directory Password' or 'Active Directory Integrated'
  • `true` in all other cases.
| | `TrustServerCertificate` |'false'|When set to `true`, SSL is used to encrypt the channel when bypassing walking the certificate chain to validate trust. If TrustServerCertificate is set to `true` and Encrypt is set to `false`, the channel is not encrypted. Recognized values are `true`, `false`, `yes`, and `no`. For more information, see [Connection String Syntax](/dotnet/framework/data/adonet/connection-string-syntax).| | `Type System Version` |N/A|A string value that indicates the type system the application expects. The functionality available to a client application is dependent on the version of SQL Server and the compatibility level of the database. 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. **Note:** The type system version cannot be set for common language runtime (CLR) code executing in-process in SQL Server. For more information, see [SQL Server Common Language Runtime Integration](/dotnet/framework/data/adonet/sql/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;` specifies that the application will require version 11.0.0.0 of Microsoft.SqlServer.Types.dll. The other `Type System Version` settings will require version 10.0.0.0 of Microsoft.SqlServer.Types.dll.

`Latest` is obsolete and should not be used. `Latest` is equivalent to `Type System Version=SQL Server 2008;`.| | `User ID`
-or-
`UID`
-or-
`User` |N/A|The SQL Server login account. Not recommended. To maintain a high level of security, we strongly recommend that you use the `Integrated Security` or `Trusted_Connection` keywords instead. is a more secure way to specify credentials for a connection that uses SQL Server Authentication.

The user ID must be 128 characters or less.| | `User Instance` |'false'|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 ID`
-or-
`WSID` |The local computer name|The name of the workstation connecting to SQL Server.

The ID must be 128 characters or less.| The following list contains the valid names for connection pooling values within the . For more information, see [SQL Server Connection Pooling (ADO.NET)](/dotnet/framework/data/adonet/sql-server-connection-pooling). - `Connection Lifetime` (or `Load Balance Timeout`) - `Enlist` - `Max Pool Size` - `Min Pool Size` - `Pooling` When you set 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] > The .NET Framework Data Provider for SQL Server uses its own protocol to communicate with SQL Server. 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] > Universal data link (UDL) files are not supported for the .NET Framework Data Provider for SQL Server. > [!CAUTION] > 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). 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). If you need to construct connection strings based on user input, use , which validates the connection string and helps to eliminate this problem. For more information, see [Connection String Builders](/dotnet/framework/data/adonet/connection-string-builders). ## Examples The following example creates a and sets the property before opening the connection. :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlConnection.ConnectionString Example/CS/source.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Data.SqlClient/SqlConnection/ConnectionString/source.vb" id="Snippet1"::: ]]>
An invalid connection string argument has been supplied, or a required connection string argument has not been supplied. ADO.NET Managed Providers and DataSet Developer Center Connection Strings in ADO.NET SQL Server Connection Pooling (ADO.NET) Connecting to a Data Source in ADO.NET ADO.NET Overview
Property P:System.Data.IDbConnection.ConnectionTimeout System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [<System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)>] [System.Data.DataSysDescription("SqlConnection_ConnectionTimeout")] [<System.Data.DataSysDescription("SqlConnection_ConnectionTimeout")>] System.Int32 Gets the time to wait (in seconds) while trying to establish a connection before terminating the attempt and generating an error. The time (in seconds) to wait for a connection to open. The default value is 15 seconds. because an attempt to connect waits indefinitely. ## Examples The following example creates a and sets the `Connection Timeout` to 30 seconds in the connection string. The code opens the connection and displays the property in the console window. :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlConnection.ConnectionTimeout Example/CS/source.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Data.SqlClient/SqlConnection/ConnectionTimeout/source.vb" id="Snippet1"::: ]]> The value set is less than 0. Connection Strings in ADO.NET SQL Server Connection Pooling (ADO.NET) Connecting to a Data Source in ADO.NET ADO.NET Overview Method System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 System.Data.SqlClient.SqlCommand Creates and returns a object associated with the . A object. ADO.NET Overview Method System.Data.SqlClient 4.1.0.0 System.Data 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 System.Data.Common.DbCommand To be added. To be added. To be added. Property System.Data 4.0.0.0 System.Data.SqlClient 4.6.1.6 [System.ComponentModel.Browsable(false)] [<System.ComponentModel.Browsable(false)>] [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [<System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)>] System.Data.SqlClient.SqlCredential Gets or sets the object for this connection. The object for this connection. object with . The default value of is null. An exception will be raised: - If is set on an open connection. - If is set when `Context Connection=true`. - If is set when `Integrated Security = true`. - If is set when the connection string uses `Password`. - If is set when the connection string uses `UserID`. ]]> ADO.NET Overview Property P:System.Data.IDbConnection.Database System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [<System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)>] [System.Data.DataSysDescription("SqlConnection_Database")] [<System.Data.DataSysDescription("SqlConnection_Database")>] System.String Gets the name of the current database or the database to be used after a connection is opened. The name of the current database or the name of the database to be used after a connection is opened. The default value is an empty string. property updates dynamically. If you change the current database using a Transact-SQL statement or the method, an informational message is sent and the property is updated automatically. ## Examples The following example creates a and displays some of its read-only properties. :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlConnection.Database Example/CS/source.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Data.SqlClient/SqlConnection/ChangeDatabase/source.vb" id="Snippet1"::: ]]> Connecting to a Data Source in ADO.NET Commands and Parameters ADO.NET Overview Property System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [<System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)>] [System.Data.DataSysDescription("SqlConnection_DataSource")] [<System.Data.DataSysDescription("SqlConnection_DataSource")>] [System.ComponentModel.Browsable(true)] [<System.ComponentModel.Browsable(true)>] System.String Gets the name of the instance of SQL Server to which to connect. The name of the instance of SQL Server to which to connect. The default value is an empty string. [!NOTE] > The property returns `null` if the connection string for the is "context connection=true". ## Examples The following example creates a and displays some of its read-only properties. :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlConnection.DataSource Example/CS/source.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Data.SqlClient/SqlConnection/DataSource/source.vb" id="Snippet1"::: ]]> Connecting to a Data Source in ADO.NET ADO.NET Overview Property System.Data 2.0.0.0 4.0.0.0 System.Data.SqlClient 4.6.1.6 System.Data.Common.DbProviderFactory To be added. To be added. To be added. Method System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 System.Void To be added. To be added. To be added. Method System.Data 1.0.5000.0 2.0.0.0 4.0.0.0 System.Data.SqlClient System.Void A reference to an existing in which to enlist. Enlists in the specified transaction as a distributed transaction. method to enlist in a distributed transaction. Because it enlists a connection in a instance, **EnlistTransaction** takes advantage of functionality available in the namespace for managing distributed transactions, making it preferable to **EnlistDistributedTransaction** for this purpose. For more information, see [Distributed Transactions](/dotnet/framework/data/adonet/distributed-transactions). You can continue to enlist in an existing distributed transaction using the **EnlistDistributedTransaction** method if auto-enlistment is disabled. Enlisting in an existing distributed transaction makes sure that, if the transaction is committed or rolled back, modifications made by the code at the data source are also committed or rolled back. `EnlistDistributedTransaction` returns an exception if the has already started a transaction using . However, if the transaction is a local transaction started at the data source (for example, by explicitly executing the BEGIN TRANSACTION statement using an object), **EnlistDistributedTransaction** rolls back the local transaction and enlists in the existing distributed transaction as requested. You do not receive notice that the local transaction was rolled back, and are responsible for managing any local transactions not started using . ]]> Transactions (ADO.NET) ADO.NET Overview Method System.Data 2.0.0.0 4.0.0.0 System.Data.SqlClient 4.6.1.6 System.Void A reference to an existing in which to enlist. Enlists in the specified transaction as a distributed transaction. method to enlist in a distributed transaction. Because it enlists a connection in a instance, **EnlistTransaction** takes advantage of functionality available in the namespace for managing distributed transactions, making it preferable to **EnlistDistributedTransaction**, which uses a **System.EnterpriseServices.ITransaction** object. It also has slightly different semantics: once a connection is explicitly enlisted on a transaction, it cannot be unenlisted or enlisted in another transaction until the first transaction finishes. For more information about distributed transactions, see [Distributed Transactions](/dotnet/framework/data/adonet/distributed-transactions). ]]> Transactions (ADO.NET) ADO.NET Overview Property System.Data.SqlClient 4.1.0.0 System.Data 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 System.Boolean Gets or sets the property. if the property has been set; otherwise . to `true`, errors that were previously treated as exceptions are now handled as events. All events fire immediately and are handled by the event handler. If is is set to `false`, then events are handled at the end of the procedure. > [!NOTE] > An error with a severity level of 17 or above that causes the server to stop processing the command needs to be handled as an exception. In this case, an exception is thrown regardless of how the error is handled in the event. For more information on working with events, see [Connection Events](/dotnet/framework/data/adonet/connection-events). For more information on errors generated by the SQL Server engine, see [Database Engine Errors](/sql/relational-databases/errors-events/database-engine-events-and-errors). ]]> Connection Events Connecting to a Data Source (ADO.NET) ADO.NET Overview System.Data 2.0.5.0 4.0.0.0 Returns schema information for the data source of this . Obtaining Schema Information from a Database ADO.NET Overview Method System.Data 2.0.0.0 4.0.0.0 System.Data.SqlClient 4.6.1.6 System.Data.DataTable Returns schema information for the data source of this . For more information about scheme, see SQL Server Schema Collections. A that contains schema information. To be added. Obtaining Schema Information from a Database ADO.NET Overview Method System.Data 2.0.0.0 4.0.0.0 System.Data.SqlClient 4.6.1.6 System.Data.DataTable Specifies the name of the schema to return. Returns schema information for the data source of this using the specified string for the schema name. A that contains schema information. is specified as null. Obtaining Schema Information from a Database ADO.NET Overview Method System.Data 2.0.0.0 4.0.0.0 System.Data.SqlClient 4.6.1.6 System.Data.DataTable Specifies the name of the schema to return. A set of restriction values for the requested schema. Returns schema information for the data source of this using the specified string for the schema name and the specified string array for the restriction values. A that contains schema information. , see . ]]> is specified as null. Obtaining Schema Information from a Database ADO.NET Overview Event System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 [System.Data.DataSysDescription("DbConnection_InfoMessage")] [<System.Data.DataSysDescription("DbConnection_InfoMessage")>] System.Data.SqlClient.SqlInfoMessageEventHandler Occurs when SQL Server returns a warning or informational message. delegate to listen to this event. The event occurs when a message with a severity of 10 or less is returned by SQL Server. Messages that have a severity between 11 and 20 raise an error and messages that have a severity over 20 causes the connection to close. For more information on SQL Server error levels, see [Database Engine Error Severities](/sql/relational-databases/errors-events/database-engine-error-severities). For more information and an example, see [Connection Events](/dotnet/framework/data/adonet/connection-events). ]]> Working with Connection Events ADO.NET Overview Method M:System.Data.IDbConnection.Open System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 System.Void Opens a database connection with the property settings specified by the . draws an open connection from the connection pool if one is available. Otherwise, it establishes a new connection to an instance of SQL Server. > [!NOTE] > If the goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling . > [!NOTE] > If you specify a port number other than 1433 when you are trying to connect to an instance of SQL Server and using a protocol other than TCP/IP, the method fails. To specify a port number other than 1433, include "server=machinename,port number" in the connection string, and use the TCP/IP protocol. > [!NOTE] > The .NET Framework Data Provider for SQL Server requires the Security permission with "Allows calls to unmanaged assemblies" enabled ( with set to `UnmanagedCode`) to open a with SQL Debugging enabled. ## Examples The following example creates a , opens it, and displays some of its properties. The connection is automatically closed at the end of the `using` block. :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlConnection.Open Example/CS/source.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Data.SqlClient/SqlConnection/Close/source.vb" id="Snippet1"::: ]]> Cannot open a connection without specifying a data source or server. or The connection is already open. A connection-level error occurred while opening the connection. If the property contains the value 18487 or 18488, this indicates that the specified password has expired or must be reset. See the method for more information. The tag in the app.config file has invalid or unknown elements. There are two entries with the same name in the section. Connection Strings in ADO.NET SQL Server Connection Pooling (ADO.NET) Connecting to a Data Source in ADO.NET ADO.NET Overview Method System.Data.SqlClient 4.1.0.0 System.Data 4.0.0.0 netstandard 2.0.0.0 System.Threading.Tasks.Task The cancellation instruction. An asynchronous version of , which opens a database connection with the property settings specified by the . The cancellation token can be used to request that the operation be abandoned before the connection timeout elapses. Exceptions will be propagated via the returned Task. If the connection timeout time elapses without successfully connecting, the returned Task will be marked as faulted with an Exception. The implementation returns a Task without blocking the calling thread for both pooled and non-pooled connections. A task representing the asynchronous operation. , must return until the returned is completed. Then, if the connection was successful, must return . If the connection fails, must return . A call to will attempt to cancel or close the corresponding call. For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see [Asynchronous Programming](/dotnet/framework/data/adonet/asynchronous-programming). This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . ]]> Calling more than once for the same instance before task completion. is specified in the connection string. A connection was not available from the connection pool before the connection time out elapsed. Any error returned by SQL Server that occurred while opening the connection. ADO.NET Overview The cancellation token was canceled. This exception is stored into the returned task. Property System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [<System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)>] [System.Data.DataSysDescription("SqlConnection_PacketSize")] [<System.Data.DataSysDescription("SqlConnection_PacketSize")>] System.Int32 Gets the size (in bytes) of network packets used to communicate with an instance of SQL Server. The size (in bytes) of network packets. The default value is 8000. ), which is sufficient for most data transfer operations. For most applications, the default packet size is best. may be a value in the range of 512 and 32767 bytes. An exception is generated if the value is outside this range. Setting the default value to a number greater than 8000 will cause the packets to use the MultiPage allocator on the instance of SQL Server instead of the much more efficient SinglePage allocator, reducing the overall scalability of the SQL Server. For more information on how SQL Server uses memory, see [Memory Management Architecture Guide](/sql/relational-databases/memory-management-architecture-guide). ## Examples The following example creates a , including setting the `Packet Size` to 512 in the connection string. It displays the and properties in the console window. :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlConnection.PacketSize Example/CS/source.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Data.SqlClient/SqlConnection/PacketSize/source.vb" id="Snippet1"::: ]]> Connecting to a Data Source in ADO.NET ADO.NET Overview Method System.Data 4.0.0.0 System.Data.SqlClient System.Void The custom providers. Registers the column encryption key store providers. customKeyStoreProviders = new Dictionary(); MySqlClientHSMProvider myProvider = new MySqlClientHSMProvider(); customKeyStoreProviders.Add(@"HSM Provider", myProvider); SqlConnection.RegisterColumnEncryptionKeyStoreProviders(customKeyStoreProviders) ``` ]]> Method System.Data.SqlClient 4.1.0.0 System.Data 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 System.Void If statistics gathering is enabled, all values are reset to zero. Provider Statistics for SQL Server (ADO.NET) ADO.NET Overview Method System.Data.SqlClient 4.1.0.0 System.Data 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 System.Collections.IDictionary Returns a name value pair collection of statistics at the point in time the method is called. Returns a reference of type of items. Provider Statistics for SQL Server (ADO.NET) ADO.NET Overview Property System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 [System.ComponentModel.Browsable(false)] [<System.ComponentModel.Browsable(false)>] [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [<System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)>] [System.Data.DataSysDescription("SqlConnection_ServerVersion")] [<System.Data.DataSysDescription("SqlConnection_ServerVersion")>] System.String Gets a string that contains the version of the instance of SQL Server to which the client is connected. The version of the instance of SQL Server. was called while the returned Task was not completed and the connection was not opened after a call to . ## Examples The following example creates a and displays the property. :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData ISqlConnection.ServerVersion Example/CS/source.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Data.SqlClient/SqlConnection/ServerVersion/source.vb" id="Snippet1"::: ]]> The connection is closed. was called while the returned Task was not completed and the connection was not opened after a call to . SQL Server and ADO.NET ADO.NET Overview Property P:System.Data.IDbConnection.State System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 [System.ComponentModel.Browsable(false)] [<System.ComponentModel.Browsable(false)>] [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [<System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)>] [System.Data.DataSysDescription("DbConnection_State")] [<System.Data.DataSysDescription("DbConnection_State")>] System.Data.ConnectionState Indicates the state of the during the most recent network operation performed on the connection. An enumeration. enumeration indicating the state of the . Closing and reopening the connection will refresh the value of . ]]> Connecting to a Data Source (ADO.NET) ADO.NET Overview Event System.Data 1.0.5000.0 System.Data.SqlClient [System.Data.DataSysDescription("DbConnection_StateChange")] [<System.Data.DataSysDescription("DbConnection_StateChange")>] System.Data.StateChangeEventHandler Occurs when the state of the connection changes. To be added. Property System.Data.SqlClient 4.1.0.0 System.Data 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 [System.ComponentModel.DefaultValue(false)] [<System.ComponentModel.DefaultValue(false)>] System.Boolean When set to , enables statistics gathering for the current connection. Returns if statistics gathering is enabled; otherwise . is the default. Provider Statistics for SQL Server (ADO.NET) ADO.NET Overview Method M:System.Data.IDbConnection.BeginTransaction System.Data 1.0.5000.0 System.Data.SqlClient System.Data.IDbTransaction Begins a database transaction. An object that represents the new transaction. or method. ]]> Method M:System.Data.IDbConnection.BeginTransaction(System.Data.IsolationLevel) System.Data 1.0.5000.0 System.Data.SqlClient System.Data.IDbTransaction One of the values. Begins a database transaction with the specified value. An object that represents the new transaction. or method. ]]> Method M:System.Data.IDbConnection.CreateCommand System.Data 1.0.5000.0 System.Data.SqlClient System.Data.IDbCommand Creates and returns a Command object that is associated with the connection. A Command object that is associated with the connection. To be added. Method M:System.ICloneable.Clone System.Data 1.0.5000.0 2.0.0.0 4.0.0.0 System.Data.SqlClient 4.6.1.6 System.Object Creates a new object that is a copy of the current instance. A new object that is a copy of this instance. instance is cast to an interface. This member is only supported by the .NET Compact Framework. ]]> ADO.NET Overview Property System.Data.SqlClient 4.1.0.0 System.Data 1.0.5000.0 2.0.0.0 2.0.5.0 4.0.0.0 netstandard 2.0.0.0 [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] [<System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)>] [System.Data.DataSysDescription("SqlConnection_WorkstationId")] [<System.Data.DataSysDescription("SqlConnection_WorkstationId")>] System.String Gets a string that identifies the database client. A string that identifies the database client. If not specified, the name of the client computer. If neither is specified, the value is an empty string. property corresponds to the `Workstation ID` connection string property. ## Examples The following example creates a and displays the property. :::code language="csharp" source="~/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlConnection.WorkstationId Example/CS/source.cs" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Data.SqlClient/SqlConnection/WorkstationId/source.vb" id="Snippet1"::: ]]> SQL Server and ADO.NET ADO.NET Overview