From 0dab7849267c5d9cfb613e2ccf054202ea2b378e Mon Sep 17 00:00:00 2001 From: Ben Russell Date: Thu, 5 Sep 2024 21:26:56 -0500 Subject: [PATCH 1/4] Batch 4 --- .../SqlCommandBuilder.xml | 1033 ++-- .../SqlCommandColumnEncryptionSetting.xml | 66 +- .../SqlConfigurableRetryFactory.xml | 358 +- .../SqlConnection.xml | 4700 ++++++++++++----- .../SqlConnectionAttestationProtocol.xml | 64 +- .../SqlConnectionColumnEncryptionSetting.xml | 34 +- .../SqlConnectionEncryptOption.xml | 162 +- .../SqlConnectionIPAddressPreference.xml | 76 +- .../SqlConnectionOverrides.xml | 42 +- .../SqlCredential.xml | 177 +- 10 files changed, 4557 insertions(+), 2155 deletions(-) diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlCommandBuilder.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlCommandBuilder.xml index 87ddd2c8b8..14a06cd0bf 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlCommandBuilder.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlCommandBuilder.xml @@ -1,439 +1,596 @@ - - - - - Automatically generates single-table commands that are used to reconcile changes made to a - - with the associated SQL Server database. This class cannot be inherited. - - - does not automatically generate the Transact-SQL statements required to reconcile changes made to a with the associated instance of SQL Server. However, you can create a object to automatically generate Transact-SQL statements for single-table updates if you set the property of the . Then, any additional Transact-SQL statements that you do not set are generated by the . - -The registers itself as a listener for events whenever you set the property. You can only associate one or object with each other at one time. - -To generate INSERT, UPDATE, or DELETE statements, the uses the property to retrieve a required set of metadata automatically. If you change the after the metadata has been retrieved, such as after the first update, you should call the method to update the metadata. - -The `SelectCommand` must also return at least one primary key or unique column. If none are present, an **InvalidOperation** exception is generated, and the commands are not generated. - -The also uses the , , and properties referenced by the . The user should call if one or more of these properties are modified, or if the itself is replaced. Otherwise the , , and properties retain their previous values. - -If you call , the is disassociated from the , and the generated commands are no longer used. - - -## Examples -The following example uses the , along and , to select rows from a data source. The example is passed a connection string, a query string that is a Transact-SQL SELECT statement, and a string that is the name of the database table. The example then creates a . - -[!code-csharp[SqlCommandBuilder#1](~/../sqlclient/doc/samples/SqlCommandBuilder.cs#1)] -]]> - - - - - Initializes a new instance of the - - class. - - - To be added. - - - - - The name of the - - . - - - Initializes a new instance of the - - class with the associated - - object. - - - registers itself as a listener for events that are generated by the specified in this property. - -When you create a new instance of , any existing associated with this is released. -]]> - - - - - To be added. - - - To be added. - - - To be added. - - - To be added. - - - To be added. - - - To be added. - - - - - Sets or gets the - - for an instance of the - - class. - - - A - - object. - - - To be added. - - - - - Sets or gets a string used as the catalog separator for an instance of the - - class. - - - A string that indicates the catalog separator for use with an instance of the - - class. - - - To be added. - - - - Gets or sets a object for which Transact-SQL statements are automatically generated. - A object. - - registers itself as a listener for events that are generated by the specified in this property. - -When you create a new instance of , any existing associated with this is released. - -]]> - - - - The referencing the stored procedure from which the parameter information is to be derived. The derived parameters are added to the collection of the . - Retrieves parameter information from the stored procedure specified in the and populates the collection of the specified object. - - with arbitrary Transact-SQL statements, such as a parameterized SELECT statement. - -For more information, see [Configuring parameters](/sql/connect/ado-net/configure-parameters). - -]]> - - The command text is not a valid stored procedure name. - - - To be added. - To be added. - To be added. - - - Gets the automatically generated object required to perform deletions on the database. - - method for informational or troubleshooting purposes because it returns the object to be executed. - -You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - -After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The SQL statements are first generated when the application calls either or . - -For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders). - -]]> - - - - Gets the automatically generated object required to perform deletions on the database. - The automatically generated object required to perform deletions. - - method for informational or troubleshooting purposes because it returns the object to be executed. - -You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - -After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The SQL statements are first generated when the application calls either or . - -For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders). - -]]> - - - - If , generate parameter names matching column names if possible. If , generate @p1, @p2, and so on. - Gets the automatically generated object that is required to perform deletions on the database. - The automatically generated object that is required to perform deletions. - - method for informational or troubleshooting purposes because it returns the object to be executed. - -You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - -After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The SQL statements are first generated when the application calls either or . - -The default behavior, when generating parameter names, is to use `@p1`, `@p2`, and so on for the various parameters. Passing `true` for the `useColumnsForParameterNames` parameter lets you force the to generate parameters based on the column names instead. This succeeds only if the following conditions are met: - -- The returned from the **GetSchema** method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name. - -- The generated parameter name meets the criteria specified in the returned from the **GetSchema** method call and found in the collection regular expression. - -- A returned from the **GetSchema** method call and found in the collection is specified. - -For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders). - -]]> - - - - Gets the automatically generated object that is required to perform insertions on the database. - - method for informational or troubleshooting purposes because it returns the object to be executed. - -You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - -After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . - -For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders). - -]]> - - - - Gets the automatically generated object required to perform insertions on the database. - The automatically generated object required to perform insertions. - - method for informational or troubleshooting purposes because it returns the object to be executed. - -You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - -After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . - -For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders). - -]]> - - - - If , generate parameter names matching column names if possible. If , generate @p1, @p2, and so on. - Gets the automatically generated object that is required to perform insertions on the database. - The automatically generated object that is required to perform insertions. - - method for informational or troubleshooting purposes because it returns the object to be executed. - -You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - -After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . - -The default behavior, when generating parameter names, is to use `@p1`, `@p2`, and so on for the various parameters. Passing `true` for the `useColumnsForParameterNames` parameter lets you force the to generate parameters based on the column names instead. This succeeds only if the following conditions are met: - -- The returned from the **GetSchema** method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name. - -- The generated parameter name meets the criteria specified in the returned from the **GetSchema** method call and found in the collection regular expression. - -- A returned from the **GetSchema** method call and found in the collection is specified. - -For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders). - -]]> - - - - To be added. - To be added. - To be added. - To be added. - - - To be added. - To be added. - To be added. - To be added. - - - To be added. - To be added. - To be added. - To be added. - - - To be added. - To be added. - To be added. - To be added. - - - Gets the automatically generated object required to perform updates on the database. - - method for informational or troubleshooting purposes because it returns the object to be executed. - -You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - -After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . - -For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders). - -]]> - - - - Gets the automatically generated object required to perform updates on the database. - The automatically generated object that is required to perform updates. - - method for informational or troubleshooting purposes because it returns the object to be executed. - -You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - -After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . - -For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders). - -]]> - - - - If , generate parameter names matching column names if possible. If , generate @p1, @p2, and so on. - Gets the automatically generated object required to perform updates on the database. - The automatically generated object required to perform updates. - - method for informational or troubleshooting purposes because it returns the object to be executed. - -You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - -After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . - -The default behavior, when generating parameter names, is to use `@p1`, `@p2`, and so on for the various parameters. Passing `true` for the `useColumnsForParameterNames` parameter lets you force the to generate parameters based on the column names instead. This succeeds only if the following conditions are met: - -- The returned from the **GetSchema** method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name. - -- The generated parameter name meets the criteria specified in the returned from the **GetSchema** method call and found in the collection regular expression. - -- A returned from the **GetSchema** method call and found in the collection is specified. - -For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders). - -]]> - - - - To be added. - To be added. - To be added. - To be added. - - - To be added. - To be added. - To be added. - To be added. - - - Gets or sets the starting character or characters to use when specifying SQL Server database objects, such as tables or columns, whose names contain characters such as spaces or reserved tokens. - The starting character or characters to use. The default is an empty string. - - [!NOTE] -> Although you cannot change the or properties after an insert, update, or delete command has been generated, you can change their settings after calling the `Update` method of a DataAdapter. - -]]> - - This property cannot be changed after an INSERT, UPDATE, or DELETE command has been generated. - - - Gets or sets the ending character or characters to use when specifying SQL Server database objects, such as tables or columns, whose names contain characters such as spaces or reserved tokens. - The ending character or characters to use. The default is an empty string. - - [!NOTE] -> Although you cannot change the or properties after an insert, update, or delete operation has been generated, you can change their settings after calling the `Update` method of a DataAdapter. - -]]> - - This property cannot be changed after an insert, update, or delete command has been generated. - - - Clears the commands that are associated with this command builder. - To be added. - - - Gets or sets the character to be used for the separator between the schema identifier and any other identifiers. - The character to be used as the schema separator. - - - - - - To be added. - To be added. - To be added. - - - The identifier that will have its embedded quotes removed. - Given a quoted identifier, returns the correct unquoted form of that identifier. This includes correctly unescaping any embedded quotes in the identifier. - The unquoted identifier, with embedded quotes properly unescaped. - To be added. - Connecting and Retrieving Data in ADO.NET - Using the .NET Framework Data Provider for SQL Server - Overview of the SqlClient driver - - + + + + + Automatically generates single-table commands that are used to reconcile changes made to a with the associated SQL Server database. This class cannot be inherited. + + + + The does not automatically generate the Transact-SQL statements required to reconcile changes made to a with the associated instance of SQL Server. However, you can create a object to automatically generate Transact-SQL statements for single-table updates if you set the property of the . Then, any additional Transact-SQL statements that you do not set are generated by the . + + + The registers itself as a listener for events whenever you set the property. You can only associate one or object with each other at one time. + + + To generate INSERT, UPDATE, or DELETE statements, the uses the property to retrieve a required set of metadata automatically. If you change the after the metadata has been retrieved, such as after the first update, you should call the method to update the metadata. + + + The must also return at least one primary key or unique column. If none are present, an exception is generated, and the commands are not generated. + + + The also uses the , , and properties referenced by the . The user should call if one or more of these properties are modified, or if the itself is replaced. Otherwise the , , and properties retain their previous values. + + + If you call , the is disassociated from the , and the generated commands are no longer used. + + + + + The following example uses the , along and , to select rows from a data source. The example is passed a connection string, a query string that is a Transact-SQL SELECT statement, and a string that is the name of the database table. The example then creates a . + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + namespace SqlCommandBuilderCS + { + class Program + { + static void Main() + { + string cnnst = ""; + string queryst = ""; + string tablen = ""; + DataSet ds = SelectSqlRows(cnnst, queryst, tablen); + } + + public static DataSet SelectSqlRows(string connectionString, string queryString, string tableName) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + SqlDataAdapter adapter = new SqlDataAdapter(); + adapter.SelectCommand = new SqlCommand(queryString, connection); + SqlCommandBuilder builder = new SqlCommandBuilder(adapter); + + connection.Open(); + + DataSet dataSet = new DataSet(); + adapter.Fill(dataSet, tableName); + + // code to modify data in DataSet here + + builder.GetUpdateCommand(); + + // Without the SqlCommandBuilder this line would fail + adapter.Update(dataSet, tableName); + + return dataSet; + } + } + } + } + + + + + + Initializes a new instance of the class. + + + To be added. + + + + + The name of the . + + + Initializes a new instance of the class with the associated object. + + + + The registers itself as a listener for events that are generated by the specified in this property. + + + When you create a new instance of , any existing associated with this is released. + + + + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + + + Sets or gets the for an instance of the class. + + + A object. + + + + + Sets or gets a string used as the catalog separator for an instance of the class. + + + A string that indicates the catalog separator for use with an instance of the class. + + + + + Gets or sets a object for which Transact-SQL statements are automatically generated. + + + A object. + + + + The registers itself as a listener for events that are generated by the specified in this property. + + + When you create a new instance of , any existing associated with this is released. + + + + + + The referencing the stored procedure from which the parameter information is to be derived. The derived parameters are added to the collection of the . + + + Retrieves parameter information from the stored procedure specified in the and populates the collection of the specified object. + + + + DeriveParameters overwrites any existing parameter information for the . + + + DeriveParameters requires an additional call to the database to obtain the information. If the parameter information is known in advance, it is more efficient to populate the parameters collection by setting the information explicitly. + + + You can only use DeriveParameters with stored procedures. You cannot use DeriveParameters with extended stored procedures. You cannot use DeriveParameters to populate the with arbitrary Transact-SQL statements, such as a parameterized SELECT statement. + + + For more information, see Configuring parameters. + + + + The command text is not a valid stored procedure name. + + + + + To be added. + + + To be added. + + + To be added. + + + + + Gets the automatically generated object required to perform deletions on the database. + + + + An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. + + + You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . + + + After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The SQL statements are first generated when the application calls either or . + + + For more information, see Generating Commands with CommandBuilders. + + + + + + Gets the automatically generated object required to perform deletions on the database. + + + The automatically generated object required to perform deletions. + + + + An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. + + + You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . + + + After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The SQL statements are first generated when the application calls either or . + + + For more information, see Generating Commands with CommandBuilders. + + + + + + If , generate parameter names matching column names if possible. If , generate @p1, @p2, and so on. + + + Gets the automatically generated object that is required to perform deletions on the database. + + + The automatically generated object that is required to perform deletions. + + + + An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. + + + You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . + + + After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The SQL statements are first generated when the application calls either or . + + + The default behavior, when generating parameter names, is to use @p1, @p2, and so on for the various parameters. Passing true for the useColumnsForParameterNames parameter lets you force the to generate parameters based on the column names instead. This succeeds only if the following conditions are met: + + + + The returned from the GetSchema method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name. + + + The generated parameter name meets the criteria specified in the returned from the GetSchema method call and found in the collection regular expression. + + + A returned from the GetSchema method call and found in the collection is specified. + + + + For more information, see Generating Commands with CommandBuilders. + + + + + + Gets the automatically generated object that is required to perform insertions on the database. + + + + An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. + + + You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . + + + After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . + + + For more information, see Generating Commands with CommandBuilders. + + + + + + Gets the automatically generated object required to perform insertions on the database. + + + The automatically generated object required to perform insertions. + + + + An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. + + + You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . + + + After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . + + + For more information, see Generating Commands with CommandBuilders. + + + + + + If , generate parameter names matching column names if possible. If , generate @p1, @p2, and so on. + + + Gets the automatically generated object that is required to perform insertions on the database. + + + The automatically generated object that is required to perform insertions. + + + + An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. + + + You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . + + + After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . + + + The default behavior, when generating parameter names, is to use @p1, @p2, and so on for the various parameters. Passing true for the useColumnsForParameterNames parameter lets you force the to generate parameters based on the column names instead. This succeeds only if the following conditions are met: + + + + The returned from the GetSchema method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name. + + + The generated parameter name meets the criteria specified in the returned from the GetSchema method call and found in the collection regular expression. + + + A returned from the GetSchema method call and found in the collection is specified. + + + + For more information, see Generating Commands with CommandBuilders. + + + + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + + + Gets the automatically generated object required to perform updates on the database. + + + + An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. + + + You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . + + + After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . + + + For more information, see Generating Commands with CommandBuilders. + + + + + + Gets the automatically generated object required to perform updates on the database. + + + The automatically generated object that is required to perform updates. + + + + ## Remarks + An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. + + + You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . + + + After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . + + + For more information, see Generating Commands with CommandBuilders. + + + + + + If , generate parameter names matching column names if possible. If , generate @p1, @p2, and so on. + + + Gets the automatically generated object required to perform updates on the database. + + + The automatically generated object required to perform updates. + + + + An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. + + + You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . + + + After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . + + + The default behavior, when generating parameter names, is to use @p1, @p2, and so on for the various parameters. Passing true for the useColumnsForParameterNames parameter lets you force the to generate parameters based on the column names instead. This succeeds only if the following conditions are met: + + + + The returned from the GetSchema method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name. + + + The generated parameter name meets the criteria specified in the returned from the GetSchema method call and found in the collection regular expression. + + + A returned from the GetSchema method call and found in the collection is specified. + + + + For more information, see Generating Commands with CommandBuilders. + + + + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + + + Gets or sets the starting character or characters to use when specifying SQL Server database objects, such as tables or columns, whose names contain characters such as spaces or reserved tokens. + + + The starting character or characters to use. The default is an empty string. + + + + Although you cannot change the or properties after an insert, update, or delete command has been generated, you can change their settings after calling the Update method of a DataAdapter. + + + + This property cannot be changed after an INSERT, UPDATE, or DELETE command has been generated. + + + + + Gets or sets the ending character or characters to use when specifying SQL Server database objects, such as tables or columns, whose names contain characters such as spaces or reserved tokens. + + + The ending character or characters to use. The default is an empty string. + + + + Although you cannot change the or properties after an insert, update, or delete operation has been generated, you can change their settings after calling the Update method of a DataAdapter. + + + + This property cannot be changed after an insert, update, or delete command has been generated. + + + + + Clears the commands that are associated with this command builder. + + + + + Gets or sets the character to be used for the separator between the schema identifier and any other identifiers. + + + The character to be used as the schema separator. + + + + Generally, database servers indicate the schema for a identifier by separating the schema name from the identifier with some character. For example, SQL Server uses a period, creating complete identifiers such as Person.CustomerName, where "Person" is the schema name and "CustomerName" is the identifier. Setting this property lets developers modify this behavior. + + + + + + To be added. + + + To be added. + + + To be added. + + + + + The identifier that will have its embedded quotes removed. + + + Given a quoted identifier, returns the correct unquoted form of that identifier. This includes correctly unescaping any embedded quotes in the identifier. + + + The unquoted identifier, with embedded quotes properly unescaped. + + + Connecting and Retrieving Data in ADO.NET + + + Using the .NET Framework Data Provider for SQL Server + + + Overview of the SqlClient driver + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlCommandColumnEncryptionSetting.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlCommandColumnEncryptionSetting.xml index 849c975612..e6ac404675 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlCommandColumnEncryptionSetting.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlCommandColumnEncryptionSetting.xml @@ -1,29 +1,39 @@ - - - - Note that these settings cannot be used to bypass encryption and gain access to plaintext data. For details, see Always Encrypted (Database Engine). - - - - - - - Specifies the connection does not use Always Encrypted. Should be used if no queries sent over the connection access encrypted columns. - - - Enables Always Encrypted for the query. - - - Specifies that only the results of the command should be processed by the Always Encrypted routine in the driver. Use this value when the command has no parameters that require encryption. - - - Specifies that the command should default to the Always Encrypted setting in the connection string. - - + + + + + Note that these settings cannot be used to bypass encryption and gain access to plaintext data. For details, see Always Encrypted (Database Engine). + + + + + If Always Encrypted is disabled for a query and the query has parameters that need to be encrypted (parameters that correspond to encrypted columns), the query will fail. + + + If Always Encrypted is disabled for a query and the query returns results from encrypted columns, the query will return encrypted values. The encrypted values will have the varbinary datatype. + + + + + + + Specifies the connection does not use Always Encrypted. Should be used if no queries sent over the connection access encrypted columns. + + + + + Enables Always Encrypted for the query. + + + + + Specifies that only the results of the command should be processed by the Always Encrypted routine in the driver. Use this value when the command has no parameters that require encryption. + + + + + Specifies that the command should default to the Always Encrypted setting in the connection string. + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConfigurableRetryFactory.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConfigurableRetryFactory.xml index cbeb9de0b1..1c2de2056d 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConfigurableRetryFactory.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConfigurableRetryFactory.xml @@ -1,116 +1,250 @@ - - - - - Provides different retry logic providers with a common list of transient errors. - - - - - - - An object of containing the configuration for the object. - Provides an exponential time interval retry logic provider. - A object. - - [!NOTE] -> The inner enumerator includes randomization to prevent multiple instances of the client from performing subsequent retry attempts at the same time. - -]]> + + + + + Provides different retry logic providers with a common list of transient errors. + + + + The following table shows the inner transient error list. + + + + Error Number + Description + + + 1204 + + The instance of the SQL Server Database Engine cannot obtain a LOCK resource at this time. Rerun your statement when there are fewer active users. Ask the database administrator to check the lock and memory configuration for this instance, or to check for long-running transactions. + + + + 1205 + + Transaction (Process ID) was deadlocked on resources with another process and has been chosen as the deadlock victim. Rerun the transaction. + + + + 1222 + Lock request time out period exceeded. + + + 49918 + Cannot process request. Not enough resources to process request. + + + 49919 + + Cannot process create or update request. Too many create or update operations in progress for subscription "%ld". + + + + 49920 + Cannot process request. Too many operations in progress for subscription "%ld". + + + 4060 + Cannot open database "%.*ls" requested by the login. The login failed. + + + 4221 + + Login to read-secondary failed due to long wait on 'HADR_DATABASE_WAIT_FOR_TRANSITION_TO_VERSIONING'. The replica is not available for login because row versions are missing for transactions that were in-flight when the replica was recycled. The issue can be resolved by rolling back or committing the active transactions on the primary replica. Occurrences of this condition can be minimized by avoiding long write transactions on the primary. + + + + 40143 + The service has encountered an error processing your request. Please try again. + + + 40613 + + Database '%.*ls' on server '%.*ls' is not currently available. Please retry the connection later. If the problem persists, contact customer support, and provide them the session tracing ID of '%.*ls'. + + + + 40501 + The service is currently busy. Retry the request after 10 seconds. Incident ID: %ls. Code: %d. + + + 40540 + The service has encountered an error processing your request. Please try again. + + + 40197 + The service has encountered an error processing your request. Please try again. Error code %d. + + + 10929 + + Resource ID: %d. The %s minimum guarantee is %d, maximum limit is %d and the current usage for the database is %d. However, the server is currently too busy to support requests greater than %d for this database. For more information, see http://go.microsoft.com/fwlink/?LinkId=267637. Otherwise, please try again later. + + + + 10928 + + Resource ID: %d. The %s limit for the database is %d and has been reached. For more information, see http://go.microsoft.com/fwlink/?LinkId=267637. + + + + 10060 + + An error has occurred while establishing a connection to the server. When connecting to SQL Server, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: TCP Provider, error: 0 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.) (Microsoft SQL Server, Error: 10060) + + + + 10054 + The data value for one or more columns overflowed the type used by the provider. + + + 10053 + Could not convert the data value due to reasons other than sign mismatch or overflow. + + + 997 + + A connection was successfully established with the server, but then an error occurred during the login process. (provider: Named Pipes Provider, error: 0 - Overlapped I/O operation is in progress) + + + + 233 + + A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.) (Microsoft SQL Server, Error: 233) + + + - If the `retryLogicOption` parameter was null. - If at least one of the following conditions occurs: -- `NumberOfTries` is less than 1 or bigger than 60. -- `DeltaTime` is bigger than 120 seconds. -- `MinTimeInterval` is bigger than 120 seconds. -- `MaxTimeInterval` is bigger than 120 seconds. -- `MinTimeInterval` is not less than `MaxTimeInterval`. - - - - An object of containing the configuration for the object. - Provides an incremental time interval retry logic provider. - A object. - - [!NOTE] -> The inner enumerator includes randomization to prevent multiple instances of the client from performing subsequent retry attempts at the same time. - -]]> + + + + An object of containing the configuration for the object. + + + Provides an exponential time interval retry logic provider. + + + A object. + + + + The inner enumerator includes randomization to prevent multiple instances of the client from performing subsequent retry attempts at the same time. + - If the `retryLogicOption` parameter was null. - If at least one of the following conditions occurs: -- `NumberOfTries` is less than 1 or bigger than 60. -- `DeltaTime` is bigger than 120 seconds. -- `MinTimeInterval` is bigger than 120 seconds. -- `MaxTimeInterval` is bigger than 120 seconds. -- `MinTimeInterval` is not less than `MaxTimeInterval`. - - - - An object of containing the configuration for the object. - Provides a fixed interval time retry logic provider. - A object. - - [!NOTE] -> The inner enumerator includes randomization to prevent multiple instances of the client from performing subsequent retry attempts at the same time. - -]]> + + If the parameter was null. + + + If at least one of the following conditions occurs: + + + is less than 1 or bigger than 60. + + + is bigger than 120 seconds. + + + is bigger than 120 seconds. + + + is bigger than 120 seconds. + + + is not less than . + + + + + + + An object of containing the configuration for the object. + + + Provides an incremental time interval retry logic provider. + + + A object. + + + + The inner enumerator includes randomization to prevent multiple instances of the client from performing subsequent retry attempts at the same time. + - If the `retryLogicOption` parameter was null. - If at least one of the following conditions occurs: -- `NumberOfTries` is less than 1 or bigger than 60. -- `DeltaTime` is bigger than 120 seconds. -- `MinTimeInterval` is bigger than 120 seconds. -- `MaxTimeInterval` is bigger than 120 seconds. -- `MinTimeInterval` is not less than `MaxTimeInterval`. - - - - Provides a non-retriable provider with a that returns . - A object. - - [!NOTE] -> The returned provider of this function performs a single execution without any retry logic. - -]]> - - - - + + If the parameter was null. + + + If at least one of the following conditions occurs: + + + is less than 1 or bigger than 60. + + + is bigger than 120 seconds. + + + is bigger than 120 seconds. + + + is bigger than 120 seconds. + + + is not less than . + + + + + + + An object of containing the configuration for the object. + + + Provides a fixed interval time retry logic provider. + + + A object. + + + + The inner enumerator includes randomization to prevent multiple instances of the client from performing subsequent retry attempts at the same time. + + + + If the `retryLogicOption` parameter was null. + + + If at least one of the following conditions occurs: + + + is less than 1 or bigger than 60. + + + is bigger than 120 seconds. + + + is bigger than 120 seconds. + + + is bigger than 120 seconds. + + + is not less than . + + + + + + + Provides a non-retryable provider with a that returns . + + + A object. + + + + The returned provider of this function performs a single execution without any retry logic. + + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml index 8c4e2f4607..b7496601aa 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml @@ -1,1340 +1,3394 @@ - - - - - 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)](/sql/connect/ado-net/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)](/sql/connect/ado-net/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](/sql/connect/ado-net/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-csharp[SqlCommand_ExecuteNonQuery Example#1](~/../sqlclient/doc/samples/SqlCommand_ExecuteNonQuery.cs#1)] - - ]]> - - - - Initializes a new instance of the class. - - - 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-csharp[SqlConnection_SqlConnection Example#1](~/../sqlclient/doc/samples/SqlConnection_SqlConnection.cs#1)] - - ]]> - - - - 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-csharp[SqlConnection_SqlConnection1 Example#1](~/../sqlclient/doc/samples/SqlConnection_SqlConnection1.cs#1)] - - ]]> - - The supplied connection string argument failed validation. - - - 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 arguments failed validation, including validation. - - - Gets or sets the access token for the connection. - The access token for the connection. - - - 0 along with AccessToken, you must call after the access token expires to ensure the connection pool doesn't maintain those connections indefinitely. - - ]]> - - - - - Gets or sets the access token callback for the connection. - - The Func that takes a and and returns a . - - - . - - [!code-csharp[SqlConnection_AccessTokenCallback Example#1](~/../sqlclient/doc/samples/SqlConnection_AccessTokenCallback.cs#1)] - - ]]> - - The AccessTokenCallback is combined with other conflicting authentication configurations. - - - To be added. - To be added. - To be added. - To be added. - - - Starts a database transaction. - - - 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-csharp[SqlConnection_BeginTransaction Example#1](~/../sqlclient/doc/samples/SqlConnection_BeginTransaction.cs#1)] - - ]]> - - Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). - Parallel transactions are not supported. - - - 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-csharp[SqlConnection_BeginTransaction1 Example#1](~/../sqlclient/doc/samples/SqlConnection_BeginTransaction1.cs#1)] - - ]]> - - Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). - Parallel transactions are not supported. - - - 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 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-csharp[SqlConnection_BeginTransaction2 Example#1](~/../sqlclient/doc/samples/SqlConnection_BeginTransaction2.cs#1)] - - ]]> - - Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). - Parallel transactions are not supported. - - - 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-csharp[SqlConnection_BeginTransaction3 Example#1](~/../sqlclient/doc/samples/SqlConnection_BeginTransaction3.cs#1)] - - ]]> - - Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). - Parallel transactions are not supported. - - - Gets a value that indicates whether this instance supports the class. - - if this instance supports the class; otherwise, . The default is . - - - and overrides `CanCreateBatch` property to return `true`. - - ]]> - - - - 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-csharp[SqlConnection_Database Example#1](~/../sqlclient/doc/samples/SqlConnection_Database.cs#1)] - - ]]> - - The database name is not valid. - The connection is not open. - Cannot change the database. - - - Changes the SQL Server password. - - - 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 supplied 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, nor returned to, the SQL Server connection pool. - - - -## Examples - The following is a simple example of changing a password: - -```csharp -class Program { - static void Main(string[] args) { - Microsoft.Data.SqlClient.SqlConnection.ChangePassword( - "Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password", - "new_password"); - } -} - -``` - -```vb -Module Module1 - Sub Main() -Microsoft.Data.SqlClient.SqlConnection.ChangePassword( - "Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password", - "new_password") - End Sub -End Module - -``` - - The following console application demonstrates the issues involved in changing a user's password because the current password has expired. - - [!code-csharp[SqlConnection_ConnectionString1#1](~/../sqlclient/doc/samples/SqlConnection_ConnectionString1.cs#1)] - - ]]> - - The connection string includes the option to use integrated security. - - Or - - The exceeds 128 characters. - Either the or the parameter is null. - - - 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). - Changes the SQL Server password for the user indicated in the object. - To be added. - - The connection string contains any combination of , , or . - - --or- - - is greater than 128 characters. - --or- - - is not read only. - --or- - - is an empty string. - One of the parameters (, , or ) is null. - - - 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. - - ]]> - - - - 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. - - ]]> - - - - 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 ([Connectivity troubleshooting in SQL Server 2008 with the Connectivity Ring Buffer](https://go.microsoft.com/fwlink/?LinkId=207752)) for certain connection errors. If the connection ID is not in the connection ring buffer, you can assume a network error. - - ]]> - - - - 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)](/sql/connect/ado-net/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-csharp[SqlConnection_Open Example#1](~/../sqlclient/doc/samples/SqlConnection_Open.cs#1)] - - ]]> - - The connection-level error that occurred while opening the connection. - - - 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. - - - 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. - - - - - - 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. - - - - Gets the default wait time (in seconds) before terminating the attempt to execute a command and generating an error. The default is 30 seconds. - - - The time in seconds to wait for the command to execute. The default is 30 seconds. - - - - - - - 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. - -``` -"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](/sql/connect/ado-net/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 Intent

-or-

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](/sql/connect/ado-net/sql/sqlclient-support-high-availability-disaster-recovery).| -|Application Name|N/A|The name of the application. If no application name is provided, 'Framework Microsoft SqlClient Data Provider' when running on .NET Framework and 'Core Microsoft SqlClient Data Provider' otherwise.

An application name can be 128 characters or less.| -|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.| -|Attestation Protocol|NotSpecified|Gets or sets the value of Attestation Protocol.

When no value is specified, secure enclaves are disabled on the connection.

Valid values are:
`AAS`
`HGS`
`None` (Only valid in v3.1 and v4.1+))| -|Authentication|N/A|The authentication method used for [Connecting to SQL Database By Using Azure Active Directory Authentication](https://azure.microsoft.com/documentation/articles/sql-database-aad-authentication/#7-connect-to-your-database-by-using-azure-active-directory-identities).

Valid values are:

`Active Directory Integrated`, `Active Directory Interactive`, `Active Directory Password`, `Active Directory Service Principal`, `Active Directory Device Code Flow`, `Active Directory Managed Identity`, `Active Directory MSI`, `Active Directory Default`, `Sql Password`.

For additional information see [Using Azure Active Directory authentication with SqlClient](https://docs.microsoft.com/sql/connect/ado-net/sql/azure-active-directory-authentication?view=sql-server-ver15).| -|Column Encryption Setting|disabled|Enables or disables [Always Encrypted](/sql/relational-databases/security/encryption/always-encrypted-database-engine) functionality for the connection. Supported values are: `enabled` and `disabled`| -|Command Timeout|30|The default wait time (in seconds) before terminating the attempt to execute a command and generating an error.

Valid values are greater than or equal to 0 and less than or equal to 2147483647.| -|Connect Retry Count

-or-

ConnectRetryCount|1|Controls the number of reconnection attempts after the client identifies an idle connection failure. Valid values are 0 to 255. 0 means do not attempt to reconnect (disable connection resiliency).

Note: Since version 5.x the default value for non Azure endpoints is 1. For Azure SQL endpoints, the default is 2. For Azure SQL serverless or on demand endpoints, the default is 5 to improve connection success for connections to an idle or paused instance.

For additional information about idle connection resiliency, see [.NET SqlConnection parameters for connection retry](https://learn.microsoft.com/azure/azure-sql/database/troubleshoot-common-connectivity-issues?view=azuresql#net-sqlconnection-parameters-for-connection-retry) and [Technical Article - Idle Connection Resiliency](https://go.microsoft.com/fwlink/?LinkId=393996).| -|Connect Retry Interval

-or-

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 idle connection resiliency, see[.NET SqlConnection parameters for connection retry](https://learn.microsoft.com/azure/azure-sql/database/troubleshoot-common-connectivity-issues?view=azuresql#net-sqlconnection-parameters-for-connection-retry) and [Technical Article - Idle Connection Resiliency](https://go.microsoft.com/fwlink/?LinkId=393996).| -|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.| -|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)`

You can also connect to a LocalDB database as follows:

`server=(localdb)\\myInstance`

For more information about LocalDB, see [SqlClient Support for LocalDB](/sql/connect/ado-net/sql/sqlclient-support-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 application will connect.

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**.| -|Enclave Attestation Url|N/A|Gets or sets the enclave attestation URL to be used with enclave based Always Encrypted.| -|Encrypt|'true' in 4.0 and above

'false' in 3.x and below|Recognized values are:
versions 1 - 4: `true`/`yes` and `false`/`no`
versions 5+: `true`/`yes`/`mandatory`, `false`/`no`/`optional` and `strict`. When `true`, TLS encryption is used for all data sent between the client and server if the server has a certificate installed. When `strict`, TDS 8.0 TLS encryption is used and the `TrustServerCertificate` setting is ignored and treated as false. For more information, see [Connection String Syntax](/sql/connect/ado-net/connection-string-syntax).

When `Encrypt` is `mandatory` or `strict` and `TrustServerCertificate` is `false`, the server name (or IP address) in a server's 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.| -|Failover Partner SPN

-or-

FailoverPartnerSPN|N/A|The SPN for the failover partner. The default value is an empty string, which causes SqlClient to use the default, driver-generated SPN.

(Only available in v5.0+)| -|Host Name In Certificate

-or-

HostNameInCertificate|N/A|The host name to use when validating the server certificate. When not specified, the server name from the Data Source is used for certificate validation.

(Only available in v5.0+)| -|Server Certificate

-or-

ServerCertificate|N/A|The path to a certificate file to match against the SQL Server TLS/SSL certificate. The accepted certificate formats are PEM, DER, and CER. If specified, the SQL Server certificate is checked by verifying if the ServerCertificate provided is an exact match.

(Only available in v5.1+)| -|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`).| -|IP Address Preference

-or-

IPAddressPreference|IPv4First|The IP address family preference when establishing TCP connections. If `Transparent Network IP Resolution` (in .NET Framework) or `Multi Subnet Failover` is set to true, this setting has no effect. Supported values include:

`IPAddressPreference=IPv4First`

`IPAddressPreference=IPv6First`

`IPAddressPreference=UsePlatformDefault`| -|Load Balance Timeout

-or-

Connection Lifetime|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.| -|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.| -|Multiple Active Result Sets

-or-

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)](/sql/connect/ado-net/sql/multiple-active-result-sets-mars).| -|Multi Subnet Failover

-or-

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](/sql/connect/ado-net/sql/sqlclient-support-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 or access token, is not returned as part of the connection if the connection is open or has ever been in an open state. This property should only be set to `true` if your application has a specific need to read the password out of an already-opened database connection. The default value of `false` is the more secure setting; using `true` for this property opens your application to security risks such as accidentally logging or tracing the database password.

Resetting the connection string resets all connection string values including the password. Recognized values are `true`, `false`, `yes`, and `no`.| -|Pool Blocking Period

-or-

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.| -|Server SPN

-or-

ServerSPN|N/A|The SPN for the data source. The default value is an empty string, which causes SqlClient to use the default, driver-generated SPN.

(Only available in v5.0+)| -|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.0, 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.| -|Transparent Network IP Resolution

-or-

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.
| -|Trust Server Certificate

-or-

TrustServerCertificate|'false'|When set to `true`, TLS 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](/sql/connect/ado-net/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)](/sql/connect/ado-net/sql-server-connection-pooling). - -- Connection Lifetime (or Load Balance Timeout) - -- Enlist - -- Max Pool Size - -- Min Pool Size - -- Pooling - - When you are setting keyword or connection pooling values that require a Boolean value, you can use 'yes' instead of 'true', and 'no' instead of 'false'. Integer values are represented as strings. -> [!NOTE] -> 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] -> 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). 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). If you need to construct connection strings based on user input, use the new , which validates the connection string and helps to eliminate this problem. See [Connection String Builders](/sql/connect/ado-net/connection-string-builders) for more information. - - - -## Examples - The following example creates a and sets the property before opening the connection. - - [!code-csharp[SqlConnection_ConnectionString Example#1](~/../sqlclient/doc/samples/SqlConnection_ConnectionString.cs#1)] - - ]]>
-
- An invalid connection string argument has been supplied, or a required connection string argument has not been supplied. -
- - Gets the time to wait 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-csharp[SqlConnection_ConnectionTimeout Example#1](~/../sqlclient/doc/samples/SqlConnection_ConnectionTimeout.cs#1)] - - ]]> - - The value set is less than 0. - - - Creates and returns a object associated with the . - A object. - - - - - - Returns a new instance of the class that implements the class. - A new instance of . - - - To be added. - To be added. - To be added. - - - 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 `Integrated Security = true`. - -- If is set when the connection string uses `Password`. - -- If is set when the connection string uses `UserID`. - - ]]> - - - - To be added. - To be added. - To be added. - - - 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-csharp[SqlConnection_Database Example#1](~/../sqlclient/doc/samples/SqlConnection_Database.cs#1)] - - ]]> - - - - 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. - - and displays some of its read-only properties. - - [!code-csharp[SqlConnection_DataSource Example#1](~/../sqlclient/doc/samples/SqlConnection_DataSource.cs#1)] - - ]]> - - - - To be added. - To be added. - To be added. - - - To be added. - To be added. - To be added. - - - 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](/sql/connect/ado-net/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 . - - ]]> - - - - 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](/sql/connect/ado-net/distributed-transactions). - - ]]> - - - - 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](/sql/connect/ado-net/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). - - ]]> - - - - Returns schema information for the data source of this . - - - - - - Returns schema information for the data source of this . For more information about scheme, see [SQL Server Schema Collections](/sql/connect/ado-net/sql-server-schema-collections). - A that contains schema information. - To be added. - - - 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. - - - 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. - - - - 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](/sql/connect/ado-net/connection-events). - - ]]> - - - - To be added. - To be added. - To be added. - - - 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-csharp[SqlConnection_Open Example#1](~/../sqlclient/doc/samples/SqlConnection_Open.cs#1)] - - ]]> - - 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. - - - Options to override default connection open behavior. - - 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. If overrides are specified, the first open attempt will apply the specified overrides to the open action. - -> [!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-csharp[SqlConnection_Open Example#1](~/../sqlclient/doc/samples/SqlConnection_Open.cs#1)] - -]]> - - - 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. - - - 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](/sql/connect/ado-net/asynchronous-programming). - - ]]> - - Calling more than once for the same instance before task completion. - - 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. - - - 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-csharp[SqlConnection_PacketSize Example#1](~/../sqlclient/doc/samples/SqlConnection_PacketSize.cs#1)] - - ]]> - - - - Dictionary of custom column encryption key store providers - - Registers the column encryption key store providers. This function should only be called once in an app. This does shallow copying of the dictionary so that the app cannot alter the custom provider list once it has been set. - - The built-in column master key store providers that are available for the Windows Certificate Store, CNG Store and CSP are pre-registered. - - - customKeyStoreProviders = new Dictionary(); - MySqlClientHSMProvider myProvider = new MySqlClientHSMProvider(); - customKeyStoreProviders.Add(@"HSM Provider", myProvider); - SqlConnection.RegisterColumnEncryptionKeyStoreProviders(customKeyStoreProviders); - ``` - ]]> - - - A null dictionary was provided. - - -or- - - A string key in the dictionary was null or empty. - - -or- - - A value in the dictionary was null. - - - A string key in the dictionary started with "MSSQL_". This prefix is reserved for system providers. - - - This function was called more than once. - - - - Dictionary of custom column encryption key providers - Registers the encryption key store providers on the instance. If this function has been called, any providers registered using the static methods will be ignored. This function can be called more than once. This does shallow copying of the dictionary so that the app cannot alter the custom provider list once it has been set. - - A null dictionary was provided. - - -or- - - A string key in the dictionary was null or empty. - - -or- - - A value in the dictionary was null. - - - A string key in the dictionary started with "MSSQL_". This prefix is reserved for system providers. - - - + + + + Represents a connection to a SQL Server database. This class cannot be inherited. + + + + A 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 or . and 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. + + + 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). + + + 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. + + + Using connection As New SqlConnection(connectionString) + connection.Open() + ' Do work here; connection closed on following line. + End Using + + + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + // Do work here; connection closed on following line. + } + + + 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). + + + 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) to modify security policy at the machine, user, and enterprise levels. For more information, see Security in .NET. For an example demonstrating how to use security demands, see Code Access Security and ADO.NET. + For more information about handling warning and informational messages from the server, see Connection Events. For more information about SQL Server engine errors and error messages, see Database Engine Events and Errors. + + + 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. + + + + + 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. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + namespace SqlCommandCS + { + class Program + { + static void Main() + { + string str = "Data Source=(local);Initial Catalog=Northwind;" + + "Integrated Security=SSPI"; + string qs = "SELECT OrderID, CustomerID FROM dbo.Orders;"; + CreateCommand(qs, str); + } + private static void CreateCommand(string queryString, string connectionString) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + SqlCommand command = new SqlCommand(queryString, connection); + command.Connection.Open(); + command.ExecuteNonQuery(); + } + } + } + } + + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class. + + + + When a new instance of 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. + + + + + The following example creates and opens a . + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + OpenSqlConnection(); + Console.ReadLine(); + } + + private static void OpenSqlConnection() + { + string connectionString = GetConnectionString(); + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + Console.WriteLine("ServerVersion: {0}", connection.ServerVersion); + Console.WriteLine("State: {0}", connection.State); + } + } + + static private string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file, using the + // System.Configuration.ConfigurationManager.ConnectionStrings property + return "Data Source=(local);Initial Catalog=AdventureWorks;" + + "Integrated Security=SSPI;"; + } + } + + + + + + 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. + + + + When a new instance of 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. + + + + + The following example creates and opens a . + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + OpenSqlConnection(); + Console.ReadLine(); + } + + private static void OpenSqlConnection() + { + string connectionString = GetConnectionString(); + + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + + Console.WriteLine("State: {0}", connection.State); + Console.WriteLine("ConnectionString: {0}", + connection.ConnectionString); + } + } + + static private string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file, using the + // System.Configuration.ConfigurationSettings.AppSettings property + return "Data Source=(local);Initial Catalog=AdventureWorks;" + + "Integrated Security=SSPI;"; + } + } + + + + The supplied connection string argument failed validation. + + + + + A connection string that does not use any of the following connection string keywords: Integrated Security = true, UserId, or Password ; or that does not use ConnectionContext = true. + + + A object. If is null, is functionally equivalent to . + + + Initializes a new instance of the class given a connection string, that does not use Integrated Security = true and a object that contains the user ID and password. + + + The supplied arguments failed validation, including validation. + + + + + Gets or sets the access token for the connection. + + + The access token for the connection. + + + The AccessToken is a part of the connection pool key. Care should be taken when using this property to manage your own access token. The application is responsible for knowing when the token expires and connections from the pool should no longer be used. If you set a minimum pool size > 0 along with AccessToken, you must call after the access token expires to ensure the connection pool doesn't maintain those connections indefinitely. + + + + + Gets or sets the access token callback for the connection. + + + The Func that takes a and and returns a . + + + + The following example demonstrates how to define and set an . + + + + using System; + using System.Data; + using Azure.Identity; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + OpenSqlConnection(); + Console.ReadLine(); + } + + private static void OpenSqlConnection() + { + const string defaultScopeSuffix = "/.default"; + string connectionString = GetConnectionString(); + DefaultAzureCredential credential = new(); + + using (SqlConnection connection = new(connectionString) + { + AccessTokenCallback = async (authParams, cancellationToken) => + { + string scope = authParams.Resource.EndsWith(defaultScopeSuffix) + ? authParams.Resource + : $"{authParams.Resource}{defaultScopeSuffix}"; + AccessToken token = await credential.GetTokenAsync( + new TokenRequestContext([scope]), + cancellationToken); + + return new SqlAuthenticationToken(token.Token, token.ExpiresOn); + } + }) + { + connection.Open(); + Console.WriteLine("ServerVersion: {0}", connection.ServerVersion); + Console.WriteLine("State: {0}", connection.State); + } + } + } + + + + The is combined with other conflicting authentication configurations. + + + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + + + Starts a database transaction. + + + + + Starts a database transaction. + + + An object representing the new transaction. + + + + This command maps to the SQL Server implementation of BEGIN TRANSACTION.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. + + + 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. + + + 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 . + + + When your query returns a large amount of data and calls , 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). + + + + + The following example creates a and a . It also demonstrates how to use the , a , and methods. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + namespace Transaction1Cs + { + class Program + { + static void Main() + { + string connectionString = + "Persist Security Info=False;Integrated Security=SSPI;database=Northwind;server=(local)"; + ExecuteSqlTransaction(connectionString); + Console.ReadLine(); + } + private static void ExecuteSqlTransaction(string connectionString) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + + SqlCommand command = connection.CreateCommand(); + SqlTransaction transaction; + + // Start a local transaction. + transaction = connection.BeginTransaction(); + + // Must assign both transaction object and connection + // to Command object for a pending local transaction + command.Connection = connection; + command.Transaction = transaction; + + try + { + command.CommandText = + "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"; + command.ExecuteNonQuery(); + command.CommandText = + "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"; + command.ExecuteNonQuery(); + + // Attempt to commit the transaction. + transaction.Commit(); + Console.WriteLine("Both records are written to database."); + } + catch (Exception ex) + { + Console.WriteLine("Commit Exception Type: {0}", ex.GetType()); + Console.WriteLine(" Message: {0}", ex.Message); + + // Attempt to roll back the transaction. + try + { + transaction.Rollback(); + } + catch (Exception ex2) + { + // This catch block will handle any errors that may have occurred + // on the server that would cause the rollback to fail, such as + // a closed connection. + Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType()); + Console.WriteLine(" Message: {0}", ex2.Message); + } + } + } + } + } + } + + + + Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). + + + Parallel transactions are not supported. + + + + + The isolation level under which the transaction should run. + + + Starts a database transaction with the specified isolation level. + + + An object representing the new transaction. + + + + This command maps to the SQL Server implementation of BEGIN TRANSACTION. 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. + + + 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. + + + For more information on SQL Server transactions, see Transactions (Transact-SQL). + + + When your query returns a large amount of data and calls , 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. + + + + + The following example creates a and a . It also demonstrates how to use the , a , and methods. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + string connectionString = + "Persist Security Info=False;Integrated Security=SSPI;database=Northwind;server=(local)"; + ExecuteSqlTransaction(connectionString); + Console.ReadLine(); + } + + private static void ExecuteSqlTransaction(string connectionString) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + + SqlCommand command = connection.CreateCommand(); + SqlTransaction transaction; + + // Start a local transaction. + transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted); + + // Must assign both transaction object and connection + // to Command object for a pending local transaction + command.Connection = connection; + command.Transaction = transaction; + + try + { + command.CommandText = + "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"; + command.ExecuteNonQuery(); + command.CommandText = + "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"; + command.ExecuteNonQuery(); + transaction.Commit(); + Console.WriteLine("Both records are written to database."); + } + catch (Exception e) + { + try + { + transaction.Rollback(); + } + catch (SqlException ex) + { + if (transaction.Connection != null) + { + Console.WriteLine("An exception of type " + ex.GetType() + + " was encountered while attempting to roll back the transaction."); + } + } + + Console.WriteLine("An exception of type " + e.GetType() + + " was encountered while inserting the data."); + Console.WriteLine("Neither record was written to database."); + } + } + } + } + + + + Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). + + + Parallel transactions are not supported. + + + + + The name of the transaction. + + + Starts a database transaction with the specified transaction name. + + + An object representing the new transaction. + + + + This command maps to the SQL Server implementation of BEGIN TRANSACTION. The length of the parameter must not exceed 32 characters; otherwise an exception will be thrown. The value in the parameter can be used in later calls to 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 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). + + + When your query returns a large amount of data and calls , 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. + + + + + The following example creates a and a . It also demonstrates how to use the , a , and methods. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + namespace Transaction1CS + { + class Program + { + static void Main() + { + string connectionString = + "Persist Security Info=False;Integrated Security=SSPI;database=Northwind;server=(local)"; + ExecuteSqlTransaction(connectionString); + Console.ReadLine(); + } + + private static void ExecuteSqlTransaction(string connectionString) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + + SqlCommand command = connection.CreateCommand(); + SqlTransaction transaction; + + // Start a local transaction. + transaction = connection.BeginTransaction("SampleTransaction"); + + // Must assign both transaction object and connection + // to Command object for a pending local transaction + command.Connection = connection; + command.Transaction = transaction; + + try + { + command.CommandText = + "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"; + command.ExecuteNonQuery(); + command.CommandText = + "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"; + command.ExecuteNonQuery(); + + // Attempt to commit the transaction. + transaction.Commit(); + Console.WriteLine("Both records are written to database."); + } + catch (Exception ex) + { + Console.WriteLine("Commit Exception Type: {0}", ex.GetType()); + Console.WriteLine(" Message: {0}", ex.Message); + + // Attempt to roll back the transaction. + try + { + transaction.Rollback("SampleTransaction"); + } + catch (Exception ex2) + { + // This catch block will handle any errors that may have occurred + // on the server that would cause the rollback to fail, such as + // a closed connection. + Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType()); + Console.WriteLine(" Message: {0}", ex2.Message); + } + } + } + } + } + } + + + + Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). + + + Parallel transactions are not supported. + + + + + 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. + + + + This command maps to the SQL Server implementation of BEGIN TRANSACTION. The value in the parameter can be used in later calls to 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. + + + 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. + + + For more information on SQL Server transactions, see Transactions (Transact-SQL). + + + When your query returns a large amount of data and calls , 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. + + + + + The following example creates a and a . It also demonstrates how to use the , a , and methods. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + namespace Transaction1CS + { + class Program + { + static void Main() + { + string connectionString = + "Persist Security Info=False;Integrated Security=SSPI;database=Northwind;server=(local)"; + ExecuteSqlTransaction(connectionString); + Console.ReadLine(); + } -This does shallow copying of the dictionary so that the app cannot alter the custom provider list once it has been set. -]]> + private static void ExecuteSqlTransaction(string connectionString) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + + SqlCommand command = connection.CreateCommand(); + SqlTransaction transaction; + + // Start a local transaction. + transaction = connection.BeginTransaction( + IsolationLevel.ReadCommitted, "SampleTransaction"); + + // Must assign both transaction object and connection + // to Command object for a pending local transaction. + command.Connection = connection; + command.Transaction = transaction; + + try + { + command.CommandText = + "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"; + command.ExecuteNonQuery(); + command.CommandText = + "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"; + command.ExecuteNonQuery(); + transaction.Commit(); + Console.WriteLine("Both records are written to database."); + } + catch (Exception e) + { + try + { + transaction.Rollback("SampleTransaction"); + } + catch (SqlException ex) + { + if (transaction.Connection != null) + { + Console.WriteLine("An exception of type " + ex.GetType() + + " was encountered while attempting to roll back the transaction."); + } + } + + Console.WriteLine("An exception of type " + e.GetType() + + " was encountered while inserting the data."); + Console.WriteLine("Neither record was written to database."); + } + } + } + } + } + + + + Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). + + + Parallel transactions are not supported. + + + + + Gets a value that indicates whether this instance supports the class. + + + if this instance supports the class; otherwise, . The default is . + + + ADO.net SQL provider implemented and overrides CanCreateBatch property to return . + + + + + The name of the database to use instead of the current database. + + + Changes the current database for an open . + + + The value supplied in the parameter must be a valid database name. The parameter cannot contain a null value, an empty string, or a string with only blank characters. + + + + The following example creates a and displays some of its read-only properties. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program1 + { + static void Main() + { + string s = GetConnectionString(); + + ChangeSqlDatabase(s); + Console.ReadLine(); + } + + private static void ChangeSqlDatabase(string connectionString) + { + // Assumes connectionString represents a valid connection string + // to the AdventureWorks sample database. + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + Console.WriteLine("ServerVersion: {0}", connection.ServerVersion); + Console.WriteLine("Database: {0}", connection.Database); + + connection.ChangeDatabase("Northwind"); + Console.WriteLine("Database: {0}", connection.Database); + } + } + + static private string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file, using the + // System.Configuration.ConfigurationSettings.AppSettings property + return "Data Source=(local);Initial Catalog=AdventureWorks;" + + "Integrated Security=SSPI;"; + } + } + + + + The database name is not valid. + + + The connection is not open. + + + Cannot change the database. + + + + + Changes the SQL Server password. + + + + + 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 supplied new password. + + + When you are using SQL Server on Windows Server, developers can take advantage of functionality that lets the client application supply both the current and a new password in order to change the existing password. Applications can implement functionality such as prompting the user for a new password during initial login if the old one has expired, and this operation can be completed without administrator intervention. The method changes the SQL Server password for the user indicated in the supplied connectionString parameter to the value supplied in the 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, nor returned to, the SQL Server connection pool. + + + + The following is a simple example of changing a password: + + + class Program + { + static void Main(string[] args) + { + Microsoft.Data.SqlClient.SqlConnection.ChangePassword( + "Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password", + "new_password"); + } + } + + + Module Module1 + Sub Main() + Microsoft.Data.SqlClient.SqlConnection.ChangePassword( + "Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password", + "new_password") + End Sub + End Module + + + + + The following console application demonstrates the issues involved in changing a user's password because the current password has expired. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + try + { + DemonstrateChangePassword(); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + Console.WriteLine("Press ENTER to continue..."); + Console.ReadLine(); + } + + private static void DemonstrateChangePassword() + { + // Retrieve the connection string. In a production application, + // this string should not be contained within the source code. + string connectionString = GetConnectionString(); + + using (SqlConnection cnn = new SqlConnection()) + { + for (int i = 0; i <= 1; i++) + { + // Run this loop at most two times. If the first attempt fails, + // the code checks the Number property of the SqlException object. + // If that contains the special values 18487 or 18488, the code + // attempts to set the user's password to a new value. + // Assuming this succeeds, the second pass through + // successfully opens the connection. + // If not, the exception handler catches the exception. + try + { + cnn.ConnectionString = connectionString; + cnn.Open(); + // Once this succeeds, just get out of the loop. + // No need to try again if the connection is already open. + break; + } + catch (SqlException ex) + { + if (i == 0 && ((ex.Number == 18487) || (ex.Number == 18488))) + { + // You must reset the password. + connectionString = + ModifyConnectionString(connectionString, + GetNewPassword()); + + } + else + // Bubble all other SqlException occurrences + // back up to the caller. + throw; + } + } + SqlCommand cmd = new SqlCommand( + "SELECT ProductID, Name FROM Product", cnn); + // Use the connection and command here... + } + } + + private static string ModifyConnectionString( + string connectionString, string NewPassword) + { + + // Use the SqlConnectionStringBuilder class to modify the + // password portion of the connection string. + SqlConnectionStringBuilder builder = + new SqlConnectionStringBuilder(connectionString); + builder.Password = NewPassword; + return builder.ConnectionString; + } + + private static string GetNewPassword() + { + // In a real application, you might display a modal + // dialog box to retrieve the new password. The concepts + // are the same as for this simple console application, however. + Console.Write("Your password must be reset. Enter a new password: "); + return Console.ReadLine(); + } + + private static string GetConnectionString() + { + // For this demonstration, the connection string must + // contain both user and password information. In your own + // application, you might want to retrieve this setting + // from a config file, or from some other source. + + // In a production application, you would want to + // display a modal form that could gather user and password + // information. + SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder( + "Data Source=(local);Initial Catalog=AdventureWorks"); + + Console.Write("Enter your user id: "); + builder.UserID = Console.ReadLine(); + Console.Write("Enter your password: "); + builder.Password = Console.ReadLine(); + + return builder.ConnectionString; + } + } + + + + + + The connection string includes the option to use integrated security. + + + The exceeds 128 characters. + + + + + Either the or the parameter is null. + + + + + 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: Integrated Security = true, UserId, or Password ; or ContextConnection = true. + + + 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). + + + Changes the SQL Server password for the user indicated in the object. + + + + + The connection string contains any combination of UserId, Password, or Integrated Security=true. + + + is greater than 128 characters. + + + is not read only. + + + is an empty string. + + + + + One of the parameters (, , or ) is null. + + + + + 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. - - - Gets or sets a value that specifies the - - object bound to this command. + + + + 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 . If additional connections associated with 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. + + + + + The connection ID of the most recent connection attempt, regardless of whether the attempt succeeded or failed. - When set to null (default), the default non-retriable provider will be applied. + 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 (Connectivity troubleshooting in SQL Server 2008 with the Connectivity Ring Buffer) for certain connection errors. If the connection ID is not in the connection ring buffer, you can assume a network error. + + + + + + Closes the connection to the database. This is the preferred method of closing any open connection. + + + + The method rolls back any pending transactions. It then releases the connection to the connection pool, or closes the connection if connection pooling is disabled. + + + 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 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. + + + 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). + + + 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. + + + + + The following example creates a , opens it, displays some of its properties. The connection is automatically closed at the end of the using block. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program1 + { + static void Main() + { + string s = GetConnectionString(); + + OpenSqlConnection(s); + Console.ReadLine(); + } + + private static void OpenSqlConnection(string connectionString) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + Console.WriteLine("ServerVersion: {0}", connection.ServerVersion); + Console.WriteLine("State: {0}", connection.State); + } + } + + static private string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file, using the + // System.Configuration.ConfigurationSettings.AppSettings property + return "Data Source=(local);Initial Catalog=AdventureWorks;" + + "Integrated Security=SSPI;"; + } + } + + + + The connection-level error that occurred while opening the connection. + + + + + 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. + + + + + 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. + + + For parameterized queries, SqlClient makes a roundtrip to SQL Server for parameter metadata, to see which parameter it needs to encrypt and how (which keys and algorithms should be used). If the application calls the same query multiple times, an extra roundtrip is made to the server each time, which degrades application performance. With ColumnEncryptionQueryMetadataCacheEnabled set to true, if the same query is called multiple times, the roundtrip to the server will be made only once. The cache has a non-configurable Max size parameter that is set to 2000 queries. + + + + + 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. + + + + + Gets the default wait time (in seconds) before terminating the attempt to execute a command and generating an error. The default is 30 seconds. + + + The time in seconds to wait for the command to execute. The default is 30 seconds. + + + You can set the default wait time by using the Command Timeout keyword in the connection string. A value of 0 indicates no limit (an attempt to execute a command will wait indefinitely). + + + + + 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. + + + + The 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. + + + "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. 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 Intent or 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. + + + + + Application Name + N/A + + + The name of the application. If no application name is provided, 'Framework Microsoft SqlClient Data Provider' when running on .NET Framework and 'Core Microsoft SqlClient Data Provider' otherwise. + + + An application name can be 128 characters or fewer. + + + + + + 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. + + + + + Attestation Protocol + NotSpecified + + + Gets or sets the value of Attestation Protocol. + + + When no value is specified, secure enclaves are disabled on the connection. + + + Valid values are: + + + AAS + HGS + None (Only valid in v3.1 and v4.1+) + + + + + Authentication + N/A + + + The authentication method used for Connecting to SQL Database By Using Azure Active Directory Authentication. + + + Valid values are: + + + Active Directory Integrated + Active Directory Interactive + Active Directory Password + Active Directory Service Principal + Active Directory Device Code Flow + Active Directory Managed Identity + Active Directory MSI + Active Directory Default + Sql Password + + + For additional information see Using Azure Active Directory authentication with SqlClient. + + + + + Column Encryption Setting + disabled + + Enables or disables Always Encrypted functionality for the connection. Supported values are: enabled and disabled + + + + Command Timeout + 30 + + + The default wait time (in seconds) before terminating the attempt to execute a command and generating an error. + + + Valid values are greater than or equal to 0 and less than or equal to 2147483647. + + + + + + Connect Retry Count or ConnectRetryCount + + 1 + + + Controls the number of reconnection attempts after the client identifies an idle connection failure. Valid values are 0 to 255. 0 means do not attempt to reconnect (disable connection resiliency). + + + Note: Since version 5.x the default value for non Azure endpoints is 1. For Azure SQL endpoints, the default is 2. For Azure SQL serverless or on demand endpoints, the default is 5 to improve connection success for connections to an idle or paused instance. + + + For additional information about idle connection resiliency, see .NET SqlConnection parameters for connection retry and Technical Article - Idle Connection Resiliency. + + + + + + Connect Retry Interval or 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 idle connection resiliency, see .NET SqlConnection parameters for connection retry and Technical Article - Idle Connection Resiliency. + + + + + + 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. + + + + + + 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 fewer. + + + + + + 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) + + + You can also connect to a LocalDB database as follows: server=(localdb)\\myInstance + + + For more information about LocalDB, see SqlClient Support for LocalDB. + + + Data Source must use the TCP format or the Named Pipes format. + + + TCP format is as follows: + + + tcp:\<host name>\\<instance name>\ + tcp:\<host name>,\<TCP/IP port number> + + + 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:\\\\<host name>\pipe\\<pipe name> + + + 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 application will connect. + + + 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. + +
+
+ + Enclave Attestation Url + N/A + Gets or sets the enclave attestation URL to be used with enclave based Always Encrypted. + + + Encrypt + + true in 4.0 and above

+ false in 3.x and below +
+ + + Recognized values are: + + + + versions 1 - 4: true / yes and false / no + + + versions 5+: true / yes / mandatory, false / no / optional and strict. When true, TLS encryption is used for all data sent between the client and server if the server has a certificate installed. When strict, TDS 8.0 TLS encryption is used and the TrustServerCertificate setting is ignored and treated as false. For more information, see Connection String Syntax. + + + + When Encrypt is mandatory or strict and TrustServerCertificate is false, the server name (or IP address) in a server's 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 fewer. + + + 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. + + + + + + Failover Partner SPN or FailoverPartnerSPN + + N/A + + The SPN for the failover partner. The default value is an empty string, which causes SqlClient to use the default, driver-generated SPN. (Only available in v5.0+) + + + + + Host Name In Certificate or HostNameInCertificate + + N/A + + The host name to use when validating the server certificate. When not specified, the server name from the Data Source is used for certificate validation. (Only available in v5.0+) + + + + + Server Certificate or ServerCertificate + + N/A + + The path to a certificate file to match against the SQL Server TLS/SSL certificate. The accepted certificate formats are PEM, DER, and CER. If specified, the SQL Server certificate is checked by verifying if the ServerCertificate provided is an exact match. (Only available in v5.1+) + + + + + Initial Catalog or Database + + N/A + + + The name of the database. + + + The database name can be 128 characters or fewer. + + + + + + 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). + + + + + + IP Address Preference or IPAddressPreference + + IPv4First + + + The IP address family preference when establishing TCP connections. If Transparent Network IP Resolution (in .NET Framework) or Multi Subnet Failover is set to true, this setting has no effect. Supported values include: + + + IPAddressPreference=IPv4First + IPAddressPreference=IPv6First + IPAddressPreference=UsePlatformDefault + + + + + + Load Balance Timeout or Connection Lifetime + + 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. + + + + + 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. + + + + + + Multiple Active Result Sets or 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). + + + + + + Multi Subnet Failover or 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. + + + + + + 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 fewer. + + + + + + Persist Security Info or PersistSecurityInfo + + false + + + When set to false or no (strongly recommended), security-sensitive information, such as the password or access token, is not returned as part of the connection if the connection is open or has ever been in an open state. This property should only be set to true if your application has a specific need to read the password out of an already-opened database connection. The default value of false is the more secure setting; using true for this property opens your application to security risks such as accidentally logging or tracing the database password. + + + Resetting the connection string resets all connection string values including the password. + + + Recognized values are true, false, yes, and no. + + + + + + Pool Blocking Period or 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, and no. + + + + + Replication + false + true if replication is supported using the connection. + + + + Server SPN or ServerSPN + + N/A + + + The SPN for the data source. The default value is an empty string, which causes SqlClient to use the default, driver-generated SPN. (Only available in v5.0+) + + + + + 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.0, 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. + + + + + + Transparent Network IP Resolution or 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. + + + + + + Trust Server Certificate or TrustServerCertificate + + false + + When set to true, TLS 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. + + + + 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. + + + 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 fewer. + + + + + 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 fewer. + + +
+ + The following list contains the valid names for connection pooling values within the . For more information, see SQL Server Connection Pooling (ADO.NET). + + + Connection Lifetime (or Load Balance Timeout) + Enlist + Max Pool Size + Min Pool Size + Pooling + + + When you are setting keyword or connection pooling values that require a Boolean value, you can use yed instead of true, and no instead of false. Integer values are represented as strings. + + + 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. + + + Universal data link (UDL) files are not supported for the .NET Framework Data Provider for SQL Server. + + + 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). 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). If you need to construct connection strings based on user input, use the new , which validates the connection string and helps to eliminate this problem. See Connection String Builders for more information. + +
+ + + The following example creates a and sets the property before opening the connection. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + OpenSqlConnection(); + Console.ReadLine(); + } + + private static void OpenSqlConnection() + { + string connectionString = GetConnectionString(); + + using (SqlConnection connection = new SqlConnection()) + { + connection.ConnectionString = connectionString; + + connection.Open(); + + Console.WriteLine("State: {0}", connection.State); + Console.WriteLine("ConnectionString: {0}", + connection.ConnectionString); + } + } + + static private string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=MSSQL1;Initial Catalog=AdventureWorks;" + + "Integrated Security=true;"; + } + } + + + + An invalid connection string argument has been supplied, or a required connection string argument has not been supplied. + +
+ + + Gets the time to wait 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. + + + You can set the amount of time a connection waits to time out by using the Connect Timeout or Connection Timeout keywords in the connection string. A value of 0 indicates no limit, and should be avoided in a because an attempt to connect waits indefinitely. + + + + 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. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + OpenSqlConnection(); + Console.ReadLine(); + } + + private static void OpenSqlConnection() + { + string connectionString = GetConnectionString(); + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + Console.WriteLine("State: {0}", connection.State); + Console.WriteLine("ConnectionTimeout: {0}", + connection.ConnectionTimeout); + } + } + + static private string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file, using the + // System.Configuration.ConfigurationSettings.AppSettings property + return "Data Source=(local);Initial Catalog=AdventureWorks;" + + "Integrated Security=SSPI;Connection Timeout=30"; + } + } + + + + The value set is less than 0. + + + + + Creates and returns a object associated with the . + + + A object. + + + + + using System.Data; + using Microsoft.Data.SqlClient; + + public class A + { + public static void Main() + { + using (SqlConnection connection = new SqlConnection("Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI;")) + { + connection.Open(); + SqlCommand command = connection.CreateCommand(); + command.CommandText = "SELECT * FROM Categories ORDER BY CategoryID"; + command.CommandTimeout = 15; + command.CommandType = CommandType.Text; + } + } + } + + + + + + Returns a new instance of the class that implements the class. + + + A new instance of . + + + + + To be added. + + + To be added. + + + To be added. + + + + + Gets or sets the object for this connection. + + + The object for this connection. + + + + Persist Security Info = true is required to get the value of the object with . The default value of is null. An exception will be raised: + + + + If is set on an open connection. + + + 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. + + + + + + + To be added. + + + To be added. + + + To be added. + + + + + 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. + + + The 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. + + + + + + The following example creates a and displays some of its read-only properties. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program1 + { + static void Main() + { + string s = GetConnectionString(); + + ChangeSqlDatabase(s); + Console.ReadLine(); + } + + private static void ChangeSqlDatabase(string connectionString) + { + // Assumes connectionString represents a valid connection string + // to the AdventureWorks sample database. + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + Console.WriteLine("ServerVersion: {0}", connection.ServerVersion); + Console.WriteLine("Database: {0}", connection.Database); + + connection.ChangeDatabase("Northwind"); + Console.WriteLine("Database: {0}", connection.Database); + } + } + + static private string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file, using the + // System.Configuration.ConfigurationSettings.AppSettings property + return "Data Source=(local);Initial Catalog=AdventureWorks;" + + "Integrated Security=SSPI;"; + } + } + + + + + + 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. + + + + The following example creates a and displays some of its read-only properties. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program1 + { + static void Main() + { + string s = GetConnectionString(); + + OpenSqlConnection(s); + Console.ReadLine(); + } + + private static void OpenSqlConnection(string connectionString) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + Console.WriteLine("ServerVersion: {0}", connection.ServerVersion); + Console.WriteLine("DataSource: {0}", connection.DataSource); + } + } + + static private string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file, using the + // System.Configuration.ConfigurationSettings.AppSettings property + return "Data Source=(local);Initial Catalog=AdventureWorks;" + + "Integrated Security=SSPI;"; + } + } + + + + + + To be added. + + + To be added. + + + To be added. + + + + + To be added. + + + To be added. + + + To be added. + + + + + A reference to an existing in which to enlist. + + + Enlists in the specified transaction as a distributed transaction. + + + + You can use the 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. + + + 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 . + + + + + + A reference to an existing in which to enlist. + + + Enlists in the specified transaction as a distributed transaction. + + + You can use the 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. + + + + + Gets or sets the property. + + + if the property has been set; otherwise . + + + + When you set 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. + + + 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. For more information on errors generated by the SQL Server engine, see Database Engine Errors. + + + + + + Returns schema information for the data source of this . + + + If you attempt to retrieve schema information for more than one versioned stored procedure, the schema for the latest one only is returned. + + + + + Returns schema information for the data source of this . For more information about scheme, see [SQL Server Schema Collections](/sql/connect/ado-net/sql-server-schema-collections). + + + A that contains schema information. + + + + + 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. + + + + You may need the schema information of the database, tables or columns. This sample: + + + Uses GetSchema to get schema information. + Use schema restrictions to get the specified information. + Gets schema information of the database, tables, and some columns. + + + + + Before you run the sample, you need to create the sample database, using the following Transact-SQL: + + + USE [master] + GO -## Remarks -You must set the value for this property before opening the connection to take effect. + CREATE DATABASE [MySchool] + GO -To apply the retry logic, do the following steps before opening the connection: -1. Define the configuration parameters by using type. -2. Create a by using one of the following static methods of the class: - - - - - - - - -3. Assign the object to the `RetryLogicProvider` property. + USE [MySchool] + GO -> [!NOTE] -> Detecting retriable exceptions is a vital part of the retry pattern. Before applying retry logic, it is important to investigate exceptions and choose a retry provider that best fits your scenario. First, log your exceptions and find transient faults. + SET ANSI_NULLS ON + GO + SET QUOTED_IDENTIFIER ON + GO -> [!NOTE] -> The connection **timeout** restarts for each execution of a connection open. There is no timing overlap between these two actions. + CREATE TABLE [dbo].[Course]( + [CourseID] [nvarchar](10) NOT NULL, + [Year] [smallint] NOT NULL, + [Title] [nvarchar](100) NOT NULL, + [Credits] [int] NOT NULL, + [DepartmentID] [int] NOT NULL, + CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED ( + [CourseID] ASC, + [Year] ASC + ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + ) ON [PRIMARY] + GO -> [!NOTE] -> The default retry logic provider is not enabled unless it is configured in an application configuration file. For more information, see [Configurable retry logic and configuration file](/sql/connect/ado-net/configurable-retry-logic-config-file-sqlclient). + SET ANSI_NULLS ON + GO + SET QUOTED_IDENTIFIER ON + GO -## Example -The following sample tries to open a connection to an invalid database to simulate a condition that the database service is temporarily unavailable . You should manually create the database while the tries to establish the connection. + CREATE TABLE [dbo].[Department]( + [DepartmentID] [int] IDENTITY(1,1) NOT NULL, + [Name] [nvarchar](50) NOT NULL, + [Budget] [money] NOT NULL, + [StartDate] [datetime] NOT NULL, + [Administrator] [int] NULL, + CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED ( + [DepartmentID] ASC + ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + ) ON [PRIMARY] + GO -[!code-csharp[SqlConfigurableRetryLogic_OpenConnection#1](~/../sqlclient/doc/samples/SqlConfigurableRetryLogic_OpenConnection.cs#1)] + INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) + VALUES (N'C1045', 2012, N'Calculus', 4, 7) + INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) + VALUES (N'C1061', 2012, N'Physics', 4, 1) + INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) + VALUES (N'C2021', 2012, N'Composition', 3, 2) + INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) + VALUES (N'C2042', 2012, N'Literature', 4, 2) + SET IDENTITY_INSERT [dbo].[Department] ON + INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) + VALUES (1, N'Engineering', 350000.0000, CAST(0x0000999C00000000 AS DateTime), 2) + INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) + VALUES (2, N'English', 120000.0000, CAST(0x0000999C00000000 AS DateTime), 6) + INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) + VALUES (4, N'Economics', 200000.0000, CAST(0x0000999C00000000 AS DateTime), 4) + INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) + VALUES (7, N'Mathematics', 250024.0000, CAST(0x0000999C00000000 AS DateTime), 3) + SET IDENTITY_INSERT [dbo].[Department] OFF -]]> + ALTER TABLE [dbo].[Course] + WITH CHECK ADD + CONSTRAINT [FK_Course_Department] FOREIGN KEY([DepartmentID]) + REFERENCES [dbo].[Department] ([DepartmentID]) + GO + + ALTER TABLE [dbo].[Course] + CHECK CONSTRAINT [FK_Course_Department] + GO + + + How to Get Schema Information from Database has C# and Visual Basic versions of this code sample in a Visual Studio project. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main(string[] args) + { + using (SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=MySchool;Integrated Security=True;")) + { + conn.Open(); + + // Get the Meta Data for Supported Schema Collections + DataTable metaDataTable = conn.GetSchema("MetaDataCollections"); + + Console.WriteLine("Meta Data for Supported Schema Collections:"); + ShowDataTable(metaDataTable, 25); + Console.WriteLine(); + + // Get the schema information of Databases in your instance + DataTable databasesSchemaTable = conn.GetSchema("Databases"); + + Console.WriteLine("Schema Information of Databases:"); + ShowDataTable(databasesSchemaTable, 25); + Console.WriteLine(); + + // First, get schema information of all the tables in current database; + DataTable allTablesSchemaTable = conn.GetSchema("Tables"); + + Console.WriteLine("Schema Information of All Tables:"); + ShowDataTable(allTablesSchemaTable, 20); + Console.WriteLine(); + + // You can specify the Catalog, Schema, Table Name, Table Type to get + // the specified table(s). + // You can use four restrictions for Table, so you should create a 4 members array. + String[] tableRestrictions = new String[4]; + + // For the array, 0-member represents Catalog; 1-member represents Schema; + // 2-member represents Table Name; 3-member represents Table Type. + // Now we specify the Table Name of the table what we want to get schema information. + tableRestrictions[2] = "Course"; + + DataTable courseTableSchemaTable = conn.GetSchema("Tables", tableRestrictions); + + Console.WriteLine("Schema Information of Course Tables:"); + ShowDataTable(courseTableSchemaTable, 20); + Console.WriteLine(); + + // First, get schema information of all the columns in current database. + DataTable allColumnsSchemaTable = conn.GetSchema("Columns"); + + Console.WriteLine("Schema Information of All Columns:"); + ShowColumns(allColumnsSchemaTable); + Console.WriteLine(); + + // You can specify the Catalog, Schema, Table Name, Column Name to get the specified column(s). + // You can use four restrictions for Column, so you should create a 4 members array. + String[] columnRestrictions = new String[4]; + + // For the array, 0-member represents Catalog; 1-member represents Schema; + // 2-member represents Table Name; 3-member represents Column Name. + // Now we specify the Table_Name and Column_Name of the columns what we want to get schema information. + columnRestrictions[2] = "Course"; + columnRestrictions[3] = "DepartmentID"; + + DataTable departmentIDSchemaTable = conn.GetSchema("Columns", columnRestrictions); + + Console.WriteLine("Schema Information of DepartmentID Column in Course Table:"); + ShowColumns(departmentIDSchemaTable); + Console.WriteLine(); + + // First, get schema information of all the IndexColumns in current database + DataTable allIndexColumnsSchemaTable = conn.GetSchema("IndexColumns"); + + Console.WriteLine("Schema Information of All IndexColumns:"); + ShowIndexColumns(allIndexColumnsSchemaTable); + Console.WriteLine(); + + // You can specify the Catalog, Schema, Table Name, Constraint Name, Column Name to + // get the specified column(s). + // You can use five restrictions for Column, so you should create a 5 members array. + String[] indexColumnsRestrictions = new String[5]; + + // For the array, 0-member represents Catalog; 1-member represents Schema; + // 2-member represents Table Name; 3-member represents Constraint Name;4-member represents Column Name. + // Now we specify the Table_Name and Column_Name of the columns what we want to get schema information. + indexColumnsRestrictions[2] = "Course"; + indexColumnsRestrictions[4] = "CourseID"; + + DataTable courseIdIndexSchemaTable = conn.GetSchema("IndexColumns", indexColumnsRestrictions); + + Console.WriteLine("Index Schema Information of CourseID Column in Course Table:"); + ShowIndexColumns(courseIdIndexSchemaTable); + Console.WriteLine(); + } + + Console.WriteLine("Please press any key to exit..."); + Console.ReadKey(); + } + + private static void ShowDataTable(DataTable table, Int32 length) + { + foreach (DataColumn col in table.Columns) + { + Console.Write("{0,-" + length + "}", col.ColumnName); + } + Console.WriteLine(); + + foreach (DataRow row in table.Rows) + { + foreach (DataColumn col in table.Columns) + { + if (col.DataType.Equals(typeof(DateTime))) + { + Console.Write("{0,-" + length + ":d}", row[col]); + } + else if (col.DataType.Equals(typeof(Decimal))) + { + Console.Write("{0,-" + length + ":C}", row[col]); + } + else { + Console.Write("{0,-" + length + "}", row[col]); + } + } + Console.WriteLine(); + } + } + + private static void ShowDataTable(DataTable table) + { + ShowDataTable(table, 14); + } + + private static void ShowColumns(DataTable columnsTable) + { + var selectedRows = from info in columnsTable.AsEnumerable() + select new + { + TableCatalog = info["TABLE_CATALOG"], + TableSchema = info["TABLE_SCHEMA"], + TableName = info["TABLE_NAME"], + ColumnName = info["COLUMN_NAME"], + DataType = info["DATA_TYPE"] + }; + + Console.WriteLine("{0,-15}{1,-15}{2,-15}{3,-15}{4,-15}", "TableCatalog", "TABLE_SCHEMA", + "TABLE_NAME", "COLUMN_NAME", "DATA_TYPE"); + foreach (var row in selectedRows) + { + Console.WriteLine("{0,-15}{1,-15}{2,-15}{3,-15}{4,-15}", row.TableCatalog, + row.TableSchema, row.TableName, row.ColumnName, row.DataType); + } + } + + private static void ShowIndexColumns(DataTable indexColumnsTable) + { + var selectedRows = from info in indexColumnsTable.AsEnumerable() + select new + { + TableSchema = info["table_schema"], + TableName = info["table_name"], + ColumnName = info["column_name"], + ConstraintSchema = info["constraint_schema"], + ConstraintName = info["constraint_name"], + KeyType = info["KeyType"] + }; + + Console.WriteLine("{0,-14}{1,-11}{2,-14}{3,-18}{4,-16}{5,-8}", "table_schema", "table_name", "column_name", "constraint_schema", "constraint_name", "KeyType"); + foreach (var row in selectedRows) + { + Console.WriteLine("{0,-14}{1,-11}{2,-14}{3,-18}{4,-16}{5,-8}", row.TableSchema, + row.TableName, row.ColumnName, row.ConstraintSchema, row.ConstraintName, row.KeyType); + } + } + } + + + + is specified as null. + + + + + 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. + + + + The parameter can supply n depth of values, which are specified by the restrictions collection for a specific collection. In order to set values on a given restriction, and not set the values of other restrictions, you need to set the preceding restrictions to and then put the appropriate value in for the restriction that you would like to specify a value for. + + + An example of this is the "Tables" collection. If the "Tables" collection has three restrictions--database, owner, and table name--and you want to get back only the tables associated with the owner "Carl", you need to pass in the following values: null, "Carl". If a restriction value is not passed in, the default values are used for that restriction. This is the same mapping as passing in , which is different from passing in an empty string for the parameter value. In that case, the empty string ("") is considered to be the value for the specified parameter. + + + + For a code sample demonstrating , see . + + + is specified as null. + + + + + + Occurs when SQL Server returns a warning or informational message. + + + + Clients that want to process warnings or informational messages sent by the server should create an 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. + For more information and an example, see Connection Events. + + + + + + To be added. + + + To be added. + + + To be added. + + + + + Opens a database connection with the property settings specified by the . + + + + 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. + + + If the goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling . + + + 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. + + + 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. + + + + + 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. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program1 + { + static void Main() + { + string s = GetConnectionString(); + + OpenSqlConnection(s); + Console.ReadLine(); + } + + private static void OpenSqlConnection(string connectionString) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + Console.WriteLine("ServerVersion: {0}", connection.ServerVersion); + Console.WriteLine("State: {0}", connection.State); + } + } + + static private string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file, using the + // System.Configuration.ConfigurationSettings.AppSettings property + return "Data Source=(local);Initial Catalog=AdventureWorks;" + + "Integrated Security=SSPI;"; + } + } + + + + + Cannot open a connection without specifying a data source or server. + 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 <system.data.localdb> tag in the app.config file has invalid or unknown elements. + + + + There are two entries with the same name in the <localdbinstances> section. + + + + + Options to override default connection open behavior. + + + Opens a database connection with the property settings specified by the . + + + + 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. If overrides are specified, the first open attempt will apply the specified overrides to the open action. + + + If the goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling . + + + 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. + + + 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. + + + + + 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. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program1 + { + static void Main() + { + string s = GetConnectionString(); + + OpenSqlConnection(s); + Console.ReadLine(); + } + + private static void OpenSqlConnection(string connectionString) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + Console.WriteLine("ServerVersion: {0}", connection.ServerVersion); + Console.WriteLine("State: {0}", connection.State); + } + } + + static private string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file, using the + // System.Configuration.ConfigurationSettings.AppSettings property + return "Data Source=(local);Initial Catalog=AdventureWorks;" + + "Integrated Security=SSPI;"; + } + } + + + + + Cannot open a connection without specifying a data source or server. + 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 <system.data.localdb> tag in the app.config file has invalid or unknown elements. + + + There are two entries with the same name in the <localdbinstances> section. + + + + + 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. + + + + After calling , 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. + + + + Calling more than once for the same instance before task completion. + + + 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. + + + + + 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. + + + + If an application performs bulk copy operations, or sends or receives lots of text or image data, a packet size larger than the default may improve efficiency because it causes fewer network read and write operations. If an application sends and receives small amounts of information, you can set the packet size to 512 bytes (using the Packet Size value in the ), 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. + + + + + 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. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + OpenSqlConnection(); + Console.ReadLine(); + } + + private static void OpenSqlConnection() + { + string connectionString = GetConnectionString(); + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + Console.WriteLine("ServerVersion: {0}", connection.ServerVersion); + Console.WriteLine("PacketSize: {0}", connection.PacketSize); + } + } + + static private string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file, using the + // System.Configuration.ConfigurationSettings.AppSettings property + return "Data Source=(local);Initial Catalog=AdventureWorks;" + + "Integrated Security=SSPI;Packet Size=512"; + } + } + + + + + + Dictionary of custom column encryption key store providers + + + + Registers the column encryption key store providers. This function should only be called once in an app. This does shallow copying of the dictionary so that the app cannot alter the custom provider list once it has been set. + + + The built-in column master key store providers that are available for the Windows Certificate Store, CNG Store and CSP are pre-registered. + + + + + Dictionary<string, SqlColumnEncryptionKeyStoreProvider> customKeyStoreProviders = new Dictionary<string, SqlColumnEncryptionKeyStoreProvider>(); + MySqlClientHSMProvider myProvider = new MySqlClientHSMProvider(); + customKeyStoreProviders.Add(@"HSM Provider", myProvider); + SqlConnection.RegisterColumnEncryptionKeyStoreProviders(customKeyStoreProviders); + + + + + A null dictionary was provided. + A string key in the dictionary was null or empty. + A value in the dictionary was null. + + + + A string key in the dictionary started with "MSSQL_". This prefix is reserved for system providers. + + + This function was called more than once. + + + + + Dictionary of custom column encryption key providers + + + Registers the encryption key store providers on the instance. If this function has been called, any providers registered using the static methods will be ignored. This function can be called more than once. This does shallow copying of the dictionary so that the app cannot alter the custom provider list once it has been set. + + + + Custom master key store providers can be registered with the driver at three different layers. The precedence of the three registrations is as follows: + + + + The per-command registration will be checked if it is not empty. + + + If the per-command registration is empty, the per-connection registration will be checked if it is not empty. + + + If the per-connection registration is empty, the global registration will be checked. + + + + Once any key store provider is found at a registration level, the driver will NOT fall back to the other registrations to search for a provider. If providers are registered but the proper provider is not found at a level, an exception will be thrown containing only the registered providers in the registration that was checked. + + + The built-in column master key store providers that are available for the Windows Certificate Store, CNG Store and CSP are pre-registered. + + + This does shallow copying of the dictionary so that the app cannot alter the custom provider list once it has been set. + + + + + A null dictionary was provided. + A string key in the dictionary was null or empty. + A value in the dictionary was null. + + + + A string key in the dictionary started with "MSSQL_". This prefix is reserved for system providers. + + + + + Gets or sets a value that specifies the object bound to this command. + + + When set to null (default), the default non-retryable provider will be applied. + + + + ## Remarks + You must set the value for this property before opening the connection to take effect. + + + To apply the retry logic, do the following steps before opening the connection: + + + + Define the configuration parameters by using type. + + + Create a by using one of the following static methods of the class: + + + + + + + + + Assign the object to the RetryLogicProvider property. + + + + Detecting retryable exceptions is a vital part of the retry pattern. Before applying retry logic, it is important to investigate exceptions and choose a retry provider that best fits your scenario. First, log your exceptions and find transient faults. + + + The connection timeout restarts for each execution of a connection open. There is no timing overlap between these two actions. + + + The default retry logic provider is not enabled unless it is configured in an application configuration file. For more information, see Configurable retry logic and configuration file. + + + + + The following sample tries to open a connection to an invalid database to simulate a condition that the database service is temporarily unavailable . You should manually create the database while the tries to establish the connection. + + + + using System; + using Microsoft.Data.SqlClient; + + /// Detecting retriable exceptions is a vital part of the retry pattern. + /// Before applying retry logic it is important to investigate exceptions and choose a retry provider that best fits your scenario. + /// First, log your exceptions and find transient faults. + /// The purpose of this sample is to illustrate how to use this feature and the condition might not be realistic. + class RetryLogicSample + { + private const string DefaultDB = "Northwind"; + private const string CnnStringFormat = "Server=localhost; Initial Catalog={0}; Integrated Security=true; pooling=false;"; + private const string DropDatabaseFormat = "DROP DATABASE {0}"; + + // For general use + private static SqlConnection s_generalConnection = new SqlConnection(string.Format(CnnStringFormat, DefaultDB)); + + static void Main(string[] args) + { + // 1. Define the retry logic parameters + var options = new SqlRetryLogicOption() + { + NumberOfTries = 5, + MaxTimeInterval = TimeSpan.FromSeconds(20), + DeltaTime = TimeSpan.FromSeconds(1) + }; + + // 2. Create a retry provider + var provider = SqlConfigurableRetryFactory.CreateExponentialRetryProvider(options); + + // define the retrying event to report the execution attempts + provider.Retrying += (object s, SqlRetryingEventArgs e) => + { + int attempts = e.RetryCount + 1; + Console.ForegroundColor = ConsoleColor.Yellow; + Console.WriteLine($"attempt {attempts} - current delay time:{e.Delay} \n"); + Console.ForegroundColor = ConsoleColor.DarkGray; + if (e.Exceptions[e.Exceptions.Count - 1] is SqlException ex) + { + Console.WriteLine($"{ex.Number}-{ex.Message}\n"); + } + else + { + Console.WriteLine($"{e.Exceptions[e.Exceptions.Count - 1].Message}\n"); + } + + // It is not a good practice to do time-consuming tasks inside the retrying event which blocks the running task. + // Use parallel programming patterns to mitigate it. + if (e.RetryCount == provider.RetryLogic.NumberOfTries - 1) + { + Console.WriteLine("This is the last chance to execute the command before throwing the exception."); + Console.WriteLine("Press Enter when you're ready:"); + Console.ReadLine(); + Console.WriteLine("continue ..."); + } + }; + + // Open the general connection. + s_generalConnection.Open(); + + try + { + // Assume the database is being created and other services are going to connect to it. + RetryConnection(provider); + } + catch + { + // exception is thrown if connecting to the database isn't successful. + throw; + } + } + + private static void ExecuteCommand(SqlConnection cn, string command) + { + using var cmd = cn.CreateCommand(); + cmd.CommandText = command; + cmd.ExecuteNonQuery(); + } + + private static void RetryConnection(SqlRetryLogicBaseProvider provider) + { + // Change this if you already have a database with the same name in your database. + string dbName = "Invalid_DB_Open"; + + // Create a connection to an invalid database. + using var cnn = new SqlConnection(string.Format(CnnStringFormat, dbName)); + // 3. Assign the `provider` to the connection + cnn.RetryLogicProvider = provider; + Console.WriteLine($"Connecting to the [{dbName}] ..."); + // Manually execute the following command in SSMS to create the invalid database while the SqlConnection is attempting to connect to it. + // >> CREATE DATABASE Invalid_DB_Open; + Console.WriteLine($"Manually, run the 'CREATE DATABASE {dbName};' in the SQL Server before exceeding the {provider.RetryLogic.NumberOfTries} attempts."); + // the connection tries to connect to the database 5 times + Console.WriteLine("The first attempt, before getting into the retry logic."); + cnn.Open(); + Console.WriteLine($"Connected to the [{dbName}] successfully."); + + cnn.Close(); + + // Drop it after test + ExecuteCommand(s_generalConnection, string.Format(DropDatabaseFormat, dbName)); + Console.WriteLine($"The [{dbName}] is removed."); + } + } + + - - If statistics gathering is enabled, all values are reset to zero. - - - - - - Returns a name value pair collection of statistics at the point in time the method is called. - Returns a reference of type of items. - - - - - - Returns a name value pair collection of internal properties at the point in time the method is called. - Returns a reference of type of (string, object) items. - - - - - - 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-csharp[SqlConnection_ServerVersion Example#1](~/../sqlclient/doc/samples/SqlConnection_ServerVersion.cs#1)] - - ]]> - - The connection is closed. - - was called while the returned Task was not completed and the connection was not opened after a call to . - - - Gets the server process Id (SPID) of the active connection. - The server process Id (SPID) of the active connection. - Returns 0 if the connection is inactive on the client side. - - - 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 . - - ]]> - - - - Occurs when the state of the connection changes. - - - When set to , enables statistics gathering for the current connection. - Returns if statistics gathering is enabled; otherwise . is the default. - - - - - - Begins a database transaction. - An object that represents the new transaction. - - or method. - ]]> - - - - One of the values. - Begins a database transaction with the specified value. - An object that represents the new transaction. - - or method. -]]> - - - - Creates and returns a Command object that is associated with the connection. - A Command object that is associated with the connection. - To be added. - - - 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. - - ]]> - - - - 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-csharp[SqlConnection_WorkstationId Example#1](~/../sqlclient/doc/samples/SqlConnection_WorkstationId.cs#1)] - - ]]> - - - + + + If statistics gathering is enabled, all values are reset to zero. + + + If statistics gathering is not enabled and this method is called, no error is thrown. + + + + + Returns a name value pair collection of statistics at the point in time the method is called. + + + Returns a reference of type of items. + + + When this method is called, the values retrieved are those at the current point in time. If you continue using the connection, the values are incorrect. You need to re-execute the method to obtain the most current values. + + + + + Returns a name value pair collection of internal properties at the point in time the method is called. + + + Returns a reference of type of (string, object) items. + + + + When this method is called, the values retrieved are those at the current point in time. If you continue using the connection, the values are incorrect. You need to re-execute the method to obtain the most current values. + + + + Supported internal properties + Type + Information provided + Return value + + + SQLDNSCachingSupportedState + string + To indicate the IsSupported flag sent by the server for DNS Caching + "true", "false", "innerConnection is null!" + + + SQLDNSCachingSupportedStateBeforeRedirect + string + To indicate the IsSupported flag sent by the server for DNS Caching before redirection. + "true", "false", "innerConnection is null!" + + + + + + + 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. + + + The version is of the form ##.##.####, where the first two digits are the major version, the next two digits are the minor version, and the last four digits are the release version. The string is of the form major.minor.build, where major and minor are exactly two digits and build is exactly four digits. was called while the returned Task was not completed and the connection was not opened after a call to . + + + + The following example creates a and displays the property. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + namespace SqlConnection1CS + { + class Program + { + static void Main() + { + string connectionString = + "Persist Security Info=False;Integrated Security=SSPI;database=Northwind;server=(local)"; + CreateSqlConnection(connectionString); + Console.ReadLine(); + } + + private static void CreateSqlConnection(string connectionString) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + Console.WriteLine("ServerVersion: {0}", connection.ServerVersion); + Console.WriteLine("State: {0}", connection.State); + } + } + } + } + + + + The connection is closed. was called while the returned Task was not completed and the connection was not opened after a call to . + + + + + Gets the server process ID (SPID) of the active connection. + + + The server process ID (SPID) of the active connection. + + + Returns 0 if the connection is inactive on the client side. + + + + + Indicates the state of the during the most recent network operation performed on the connection. + + + An enumeration. + + + Returns an enumeration indicating the state of the . Closing and reopening the connection will refresh the value of . + + + + + Occurs when the state of the connection changes. + + + + + When set to , enables statistics gathering for the current connection. + + + Returns if statistics gathering is enabled; otherwise . is the default. + + + Enabling statistics gathering has a minor, but measurable effect on performance and therefore should be enabled only when it is required. + + + + + Begins a database transaction. + + + An object that represents the new transaction. + + + Once the transaction has completed, you must explicitly commit or roll back the transaction by using the or method. + + + + + One of the values. + + + Begins a database transaction with the specified value. + + + An object that represents the new transaction. + + + Once the transaction has completed, you must explicitly commit or roll back the transaction by using the or method. + + + + + Creates and returns a Command object that is associated with the connection. + + + A Command object that is associated with the connection. + + + + + Creates a new object that is a copy of the current instance. + + + A new object that is a copy of this instance. + + + + This member is an explicit interface member implementation. It can be used only when the instance is cast to an interface. + + + This member is only supported by the .NET Compact Framework. + + + + + + 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. + + + The string typically contains the network name of the client. The property corresponds to the Workstation ID connection string property. + + + + The following example creates a and displays the property. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + string s = GetConnectionString(); + + OpenSqlConnection(s); + Console.ReadLine(); + } + + private static void OpenSqlConnection(string connectionString) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + Console.WriteLine("ServerVersion: {0}", connection.ServerVersion); + Console.WriteLine("WorkstationId: {0}", connection.WorkstationId); + } + } + + static private string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file, using the + // System.Configuration.ConfigurationSettings.AppSettings property + return "Data Source=(local);Initial Catalog=AdventureWorks;" + + "Integrated Security=SSPI;"; + } + } + + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionAttestationProtocol.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionAttestationProtocol.xml index db98ad4fdf..3b93c3e844 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionAttestationProtocol.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionAttestationProtocol.xml @@ -1,25 +1,41 @@ - - - - - Specifies a value for Attestation Protocol. - - - - If the attestation protocol is not specified. Use this as default value. - 0 - - - Attestation portocol for Azure Attestation Service - 1 - - - Attestation protocol for no attestation. Only compatible with Virtualization-based security (VBS) enclaves. An Enclave Attestation Url is not required when using this protocol. - 2 - - - Attestation protocol for Host Guardian Service - 3 - - + + + + + Specifies a value for Attestation Protocol. + + + + + If the attestation protocol is not specified. Use this as default value. + + + 0 + + + + + Attestation protocol for Azure Attestation Service + + + 1 + + + + + Attestation protocol for no attestation. Only compatible with Virtualization-based security (VBS) enclaves. An Enclave Attestation Url is not required when using this protocol. + + + 2 + + + + + Attestation protocol for Host Guardian Service + + + 3 + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionColumnEncryptionSetting.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionColumnEncryptionSetting.xml index 7bb1126a6e..ea99bf42b8 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionColumnEncryptionSetting.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionColumnEncryptionSetting.xml @@ -1,15 +1,19 @@ - - - - - Note that these settings cannot be used to bypass encryption and gain access to plaintext data. For details, see Always Encrypted (Database Engine). - To be added. - - - Specifies the connection does not use Always Encrypted. Should be used if no queries sent over the connection access encrypted columns. - - - Enables Always Encrypted functionality for the connection. Query parameters that correspond to encrypted columns will be transparently encrypted and query results from encrypted columns will be transparently decrypted. - - - + + + + + Note that these settings cannot be used to bypass encryption and gain access to plaintext data. For details, see Always Encrypted (Database Engine). + + + + + Specifies the connection does not use Always Encrypted. Should be used if no queries sent over the connection access encrypted columns. + + + + + Enables Always Encrypted functionality for the connection. Query parameters that correspond to encrypted columns will be transparently encrypted and query results from encrypted columns will be transparently decrypted. + + + + \ No newline at end of file diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptOption.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptOption.xml index 39111465a3..d550f8d916 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptOption.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptOption.xml @@ -1,75 +1,89 @@ - - - - - These options are used to control encryption behavior of the communication between the server and the client. - - property. When converting from a boolean, a value of `true` converts to and a value of `false` converts to . When converting to a boolean, , , and `null` convert to `true` and converts `false`. - - ]]> - - - - - Converts the specified string representation of a logical value to its equivalent. - - A string containing the value to convert. - - An object that is equivalent to contained in . - - - Throws exception if provided is not convertible to type. - - - - - Converts the specified string representation of a logical value to its equivalent and returns a value that indicates whether the conversion succeeded. - - A string containing the value to convert. - - An object that is equivalent to contained in . if conversion fails. - - - if the parameter was converted successfully; otherwise, . - - This method does not throw an exception if conversion fails. - - - Specifies that TLS encryption is optional when connecting to the server. If the server requires encryption, encryption will be negotiated. - - - Specifies that TLS encryption is required when connecting to the server. If the server doesn't support encryption, the connection will fail. - - - Enables and requires TDS 8.0, TLS encryption to the server. If the server doesn't support TDS 8.0, TLS encryption, the connection will fail. - - - The boolean value to be used for implicit comparison. - - Enables implicit conversion of a boolean to a . A value of converts to . A value of converts to . - - - - The value to be used for implicit comparison. - - Enables implicit conversion of a to a boolean. and convert to . converts to . - - - - Returns the string value of . - - - - Compares the representation of to another . - - - - - Returns the hash code of the value. - - - + + + + + These options are used to control encryption behavior of the communication between the server and the client. + + + Implicit conversions have been added to maintain backwards compatibility with boolean behavior for the property. When converting from a boolean, a value of converts to and a value of converts to . When converting to a boolean, , , and convert to true and converts . + + + + + Converts the specified string representation of a logical value to its equivalent. + + + A string containing the value to convert. + + + An object that is equivalent to contained in . + + + Throws exception if provided is not convertible to type. + + + + + Converts the specified string representation of a logical value to its equivalent and returns a value that indicates whether the conversion succeeded. + + + A string containing the value to convert. + + + An object that is equivalent to contained in . if conversion fails. + + + if the parameter was converted successfully; otherwise, . + + + This method does not throw an exception if conversion fails. + + + + + Specifies that TLS encryption is optional when connecting to the server. If the server requires encryption, encryption will be negotiated. + + + + + Specifies that TLS encryption is required when connecting to the server. If the server doesn't support encryption, the connection will fail. + + + + + Enables and requires TDS 8.0, TLS encryption to the server. If the server doesn't support TDS 8.0, TLS encryption, the connection will fail. + + + + + The boolean value to be used for implicit comparison. + + + Enables implicit conversion of a boolean to a . A value of converts to . A value of converts to . + + + + + The value to be used for implicit comparison. + + + Enables implicit conversion of a to a boolean. and convert to . converts to . + + + + + Returns the string value of . + + + + + Compares the representation of to another . + + + + + Returns the hash code of the value. + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionIPAddressPreference.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionIPAddressPreference.xml index e713cb776b..c07d30ecce 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionIPAddressPreference.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionIPAddressPreference.xml @@ -1,40 +1,38 @@ - - - - - Specifies a value for IP address preference during a TCP connection. - - - - - - - - Specifies a value for IP address preference during a TCP connection. - - - - - - - Connects using IPv4 address(es) first. If the connection fails, try IPv6 address(es), if provided. This is the default value. - 0 - - - Connect using IPv6 address(es) first. If the connection fails, try IPv4 address(es), if available. - 1 - - - Connects with IP addresses in the order the underlying platform or operating system provides them. - 2 - - + + + + + Specifies a value for IP address preference during a TCP connection. + + + If Multi Subnet Failover or Transparent Network IP Resolution is set to true, this setting has no effect. + + + + + Specifies a value for IP address preference during a TCP connection. + + + If Multi Subnet Failover is set to true, this setting has no effect. + + + + + Connects using IPv4 address(es) first. If the connection fails, try IPv6 address(es), if provided. This is the default value. + + 0 + + + + Connect using IPv6 address(es) first. If the connection fails, try IPv4 address(es), if available. + + 1 + + + + Connects with IP addresses in the order the underlying platform or operating system provides them. + + 2 + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionOverrides.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionOverrides.xml index cf6c2afb93..612f0a3cba 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionOverrides.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionOverrides.xml @@ -1,17 +1,25 @@ - - - - - Specifies a value for Overrides. - - - - No overrides. - 0 - - - Disable transient fault handling during the initial SqlConnection Open attempt. - 1 - - - + + + + + Specifies a value for Overrides. + + + + + No overrides. + + + 0 + + + + + Disable transient fault handling during the initial SqlConnection Open attempt. + + + 1 + + + + \ No newline at end of file diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlCredential.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlCredential.xml index 41caafa87f..6e839a6019 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlCredential.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlCredential.xml @@ -1,86 +1,93 @@ - - - - - - provides a more secure way to specify the password for a login attempt using SQL Server Authentication. - - is comprised of a user id and a password that will be used for SQL Server Authentication. The password in a object is of type . - - cannot be inherited. - - Windows Authentication () remains the most secure way to log in to a SQL Server database. - - to get or set a connection's object. Use to change the password for a object. For information on how a object affects connection pool behavior, see [SQL Server Connection Pooling (ADO.NET)](/sql/connect/ado-net/sql-server-connection-pooling). - - An exception will be raised if a non-null object is used in a connection with any of the following connection string keywords: - -- `Integrated Security = true` - -- `Password` - -- `User ID` - - The following sample connects to a SQL Server database using : - -``` -// change connection string in the APP.CONFIG file - - - - -// then use the following snippet: -using System.Configuration; - -System.Windows.Controls.TextBox txtUserId = new System.Windows.Controls.TextBox(); -System.Windows.Controls.PasswordBox txtPwd = new System.Windows.Controls.PasswordBox(); - -Configuration config = Configuration.WebConfigurationManager.OpenWebConfiguration(Null); -ConnectionStringSettings connString = config.ConnectionStrings.ConnectionString["MyConnString"]; - -using (SqlConnection conn = new SqlConnection(connString.ConnectionString)) -{ - SecureString pwd = txtPwd.SecurePassword; - pwd.MakeReadOnly(); - SqlCredential cred = new SqlCredential(txtUserId.Text, pwd); - conn.Credential = cred; - conn.Open(); -} -``` - - ]]> - - - - The user id. - The password; a value marked as read-only. Passing a read/write parameter will raise an . - Creates an object of type . - - value is allowed. An attempt to pass a null parameter in the constructor will raise an exception. - - ]]> - - Overview of the SqlClient driver - - - Gets the password component of the object. - The password component of the object. - To be added. - Overview of the SqlClient driver - - - Gets the user ID component of the object. - The user ID component of the object. - To be added. - Overview of the SqlClient driver - - + + + + + provides a more secure way to specify the password for a login attempt using SQL Server Authentication. is comprised of a user id and a password that will be used for SQL Server Authentication. The password in a object is of type . cannot be inherited. Windows Authentication ( ) remains the most secure way to log in to a SQL Server database. + + + + Use to get or set a connection's object. Use to change the password for a object. For information on how a object affects connection pool behavior, see SQL Server Connection Pooling (ADO.NET). + + + An exception will be raised if a non-null object is used in a connection with any of the following connection string keywords: + + + Integrated Security = true + Password + User ID + + + + + The following sample connects to a SQL Server database using : + + change connection string in the APP.CONFIG file + + <!-- --> + <connectionStrings> + <add name="MyConnString" connectionString="Initial Catalog=myDB;Server=myServer" providerName="Microsoft.Data.SqlClient" /> + </connectionStrings> + + Then use the following snippet: + + using System.Configuration; + + System.Windows.Controls.TextBox txtUserId = new System.Windows.Controls.TextBox(); + System.Windows.Controls.PasswordBox txtPwd = new System.Windows.Controls.PasswordBox(); + Configuration config = Configuration.WebConfigurationManager.OpenWebConfiguration(null); + ConnectionStringSettings connString = config.ConnectionStrings.ConnectionString["MyConnString"]; + + using (SqlConnection conn = new SqlConnection(connString.ConnectionString)) + { + SecureString pwd = txtPwd.SecurePassword; + pwd.MakeReadOnly(); + + SqlCredential cred = new SqlCredential(txtUserId.Text, pwd); + conn.Credential = cred; + + conn.Open(); + } + + + + + + The user id. + + + The password; a value marked as read-only. Passing a read/write parameter will raise an . + + + Creates an object of type . + + + The constructor does not accept null parameters. A value is allowed. An attempt to pass a null parameter in the constructor will raise an exception. + + + Overview of the SqlClient driver + + + + + Gets the password component of the object. + + + The password component of the object. + + + Overview of the SqlClient driver + + + + + Gets the user ID component of the object. + + + The user ID component of the object. + + + Overview of the SqlClient driver + + + From 61ad475d4f500572c354e99ba3adc655cbbd47e7 Mon Sep 17 00:00:00 2001 From: Ben Russell Date: Thu, 12 Sep 2024 15:25:00 -0500 Subject: [PATCH 2/4] Touching up and fixing mistakes --- .../SqlCommandBuilder.xml | 100 ++----- .../SqlConfigurableRetryFactory.xml | 42 +-- .../SqlConnection.xml | 274 +++++++----------- .../SqlConnectionEncryptOption.xml | 2 +- .../SqlConnectionOverrides.xml | 4 +- .../SqlCredential.xml | 9 +- .../netcore/ref/Microsoft.Data.SqlClient.cs | 1 + .../netfx/ref/Microsoft.Data.SqlClient.cs | 1 + ...crosoft.Data.SqlClient.Batch.NetCoreApp.cs | 10 +- 9 files changed, 155 insertions(+), 288 deletions(-) diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlCommandBuilder.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlCommandBuilder.xml index 14a06cd0bf..b2b71ad4ed 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlCommandBuilder.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlCommandBuilder.xml @@ -78,9 +78,6 @@ Initializes a new instance of the class. - - To be added. - @@ -186,25 +183,6 @@ To be added. - - - Gets the automatically generated object required to perform deletions on the database. - - - - An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. - - - You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - - - After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The SQL statements are first generated when the application calls either or . - - - For more information, see Generating Commands with CommandBuilders. - - - Gets the automatically generated object required to perform deletions on the database. @@ -220,7 +198,7 @@ You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The SQL statements are first generated when the application calls either or . + After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The SQL statements are first generated when the application calls either or . For more information, see Generating Commands with CommandBuilders. @@ -245,20 +223,20 @@ You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The SQL statements are first generated when the application calls either or . + After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The SQL statements are first generated when the application calls either or . - The default behavior, when generating parameter names, is to use @p1, @p2, and so on for the various parameters. Passing true for the useColumnsForParameterNames parameter lets you force the to generate parameters based on the column names instead. This succeeds only if the following conditions are met: + The default behavior, when generating parameter names, is to use @p1, @p2, and so on for the various parameters. Passing for the parameter lets you force the command builder to generate parameters based on the column names instead. This succeeds only if the following conditions are met: - The returned from the GetSchema method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name. + The returned from the GetSchema method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name. - The generated parameter name meets the criteria specified in the returned from the GetSchema method call and found in the collection regular expression. + The generated parameter name meets the criteria specified in the returned from the GetSchema method call and found in the collection regular expression. - A returned from the GetSchema method call and found in the collection is specified. + A returned from the GetSchema method call and found in the collection is specified. @@ -266,25 +244,6 @@ - - - Gets the automatically generated object that is required to perform insertions on the database. - - - - An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. - - - You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - - - After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . - - - For more information, see Generating Commands with CommandBuilders. - - - Gets the automatically generated object required to perform insertions on the database. @@ -300,7 +259,7 @@ You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . + After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . For more information, see Generating Commands with CommandBuilders. @@ -328,17 +287,17 @@ After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . - The default behavior, when generating parameter names, is to use @p1, @p2, and so on for the various parameters. Passing true for the useColumnsForParameterNames parameter lets you force the to generate parameters based on the column names instead. This succeeds only if the following conditions are met: + The default behavior, when generating parameter names, is to use @p1, @p2, and so on for the various parameters. Passing for the parameter lets you force the command builder to generate parameters based on the column names instead. This succeeds only if the following conditions are met: - The returned from the GetSchema method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name. + The returned from the GetSchema method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name. - The generated parameter name meets the criteria specified in the returned from the GetSchema method call and found in the collection regular expression. + The generated parameter name meets the criteria specified in the returned from the GetSchema method call and found in the collection regular expression. - A returned from the GetSchema method call and found in the collection is specified. + A returned from the GetSchema method call and found in the collection is specified. @@ -402,25 +361,6 @@ To be added. - - - Gets the automatically generated object required to perform updates on the database. - - - - An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. - - - You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - - - After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . - - - For more information, see Generating Commands with CommandBuilders. - - - Gets the automatically generated object required to perform updates on the database. @@ -430,14 +370,13 @@ - ## Remarks An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . + After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . For more information, see Generating Commands with CommandBuilders. @@ -462,20 +401,20 @@ You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . + After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . - The default behavior, when generating parameter names, is to use @p1, @p2, and so on for the various parameters. Passing true for the useColumnsForParameterNames parameter lets you force the to generate parameters based on the column names instead. This succeeds only if the following conditions are met: + The default behavior, when generating parameter names, is to use @p1, @p2, and so on for the various parameters. Passing for the parameter lets you force the command builder to generate parameters based on the column names instead. This succeeds only if the following conditions are met: - The returned from the GetSchema method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name. + The returned from the GetSchema method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name. - The generated parameter name meets the criteria specified in the returned from the GetSchema method call and found in the collection regular expression. + The generated parameter name meets the criteria specified in the returned from the GetSchema method call and found in the collection regular expression. - A returned from the GetSchema method call and found in the collection is specified. + A returned from the GetSchema method call and found in the collection is specified. @@ -543,11 +482,6 @@ This property cannot be changed after an insert, update, or delete command has been generated. - - - Clears the commands that are associated with this command builder. - - Gets or sets the character to be used for the separator between the schema identifier and any other identifiers. diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConfigurableRetryFactory.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConfigurableRetryFactory.xml index 1c2de2056d..6b3a484460 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConfigurableRetryFactory.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConfigurableRetryFactory.xml @@ -11,104 +11,104 @@ Error Number - Description + Description - 1204 + 1204 The instance of the SQL Server Database Engine cannot obtain a LOCK resource at this time. Rerun your statement when there are fewer active users. Ask the database administrator to check the lock and memory configuration for this instance, or to check for long-running transactions. - 1205 + 1205 Transaction (Process ID) was deadlocked on resources with another process and has been chosen as the deadlock victim. Rerun the transaction. - 1222 + 1222 Lock request time out period exceeded. - 49918 + 49918 Cannot process request. Not enough resources to process request. - 49919 + 49919 Cannot process create or update request. Too many create or update operations in progress for subscription "%ld". - 49920 + 49920 Cannot process request. Too many operations in progress for subscription "%ld". - 4060 + 4060 Cannot open database "%.*ls" requested by the login. The login failed. - 4221 + 4221 Login to read-secondary failed due to long wait on 'HADR_DATABASE_WAIT_FOR_TRANSITION_TO_VERSIONING'. The replica is not available for login because row versions are missing for transactions that were in-flight when the replica was recycled. The issue can be resolved by rolling back or committing the active transactions on the primary replica. Occurrences of this condition can be minimized by avoiding long write transactions on the primary. - 40143 + 40143 The service has encountered an error processing your request. Please try again. - 40613 + 40613 Database '%.*ls' on server '%.*ls' is not currently available. Please retry the connection later. If the problem persists, contact customer support, and provide them the session tracing ID of '%.*ls'. - 40501 + 40501 The service is currently busy. Retry the request after 10 seconds. Incident ID: %ls. Code: %d. - 40540 + 40540 The service has encountered an error processing your request. Please try again. - 40197 + 40197 The service has encountered an error processing your request. Please try again. Error code %d. - 10929 + 10929 Resource ID: %d. The %s minimum guarantee is %d, maximum limit is %d and the current usage for the database is %d. However, the server is currently too busy to support requests greater than %d for this database. For more information, see http://go.microsoft.com/fwlink/?LinkId=267637. Otherwise, please try again later. - 10928 + 10928 Resource ID: %d. The %s limit for the database is %d and has been reached. For more information, see http://go.microsoft.com/fwlink/?LinkId=267637. - 10060 + 10060 An error has occurred while establishing a connection to the server. When connecting to SQL Server, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: TCP Provider, error: 0 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.) (Microsoft SQL Server, Error: 10060) - 10054 + 10054 The data value for one or more columns overflowed the type used by the provider. - 10053 + 10053 Could not convert the data value due to reasons other than sign mismatch or overflow. - 997 + 997 A connection was successfully established with the server, but then an error occurred during the login process. (provider: Named Pipes Provider, error: 0 - Overlapped I/O operation is in progress) - 233 + 233 A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.) (Microsoft SQL Server, Error: 233) diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml index b7496601aa..fda08fea7b 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml @@ -82,11 +82,6 @@ - - - Initializes a new instance of the class. - - Initializes a new instance of the class. @@ -98,22 +93,22 @@ Properties - Initial value + Initial value - + empty string ("") - + 15 - + empty string ("") - + empty string ("") @@ -176,22 +171,22 @@ Properties - Initial value + Initial value - + connectionString - + 15 - + empty string ("") - + empty string ("") @@ -243,12 +238,12 @@ - The supplied connection string argument failed validation. + The supplied connection string argument failed validation. - A connection string that does not use any of the following connection string keywords: Integrated Security = true, UserId, or Password ; or that does not use ConnectionContext = true. + A connection string that does not use any of the following connection string keywords: Integrated Security = true, UserId, or Password; or that does not use ConnectionContext = true. A object. If is null, is functionally equivalent to . @@ -257,7 +252,7 @@ Initializes a new instance of the class given a connection string, that does not use Integrated Security = true and a object that contains the user ID and password. - The supplied arguments failed validation, including validation. + The supplied arguments failed validation, including validation. @@ -268,7 +263,7 @@ The access token for the connection. - The AccessToken is a part of the connection pool key. Care should be taken when using this property to manage your own access token. The application is responsible for knowing when the token expires and connections from the pool should no longer be used. If you set a minimum pool size > 0 along with AccessToken, you must call after the access token expires to ensure the connection pool doesn't maintain those connections indefinitely. + The AccessToken is a part of the connection pool key. Care should be taken when using this property to manage your own access token. The application is responsible for knowing when the token expires and connections from the pool should no longer be used. If you set a minimum pool size > 0 along with AccessToken, you must call after the access token expires to ensure the connection pool doesn't maintain those connections indefinitely. @@ -276,7 +271,7 @@ Gets or sets the access token callback for the connection. - The Func that takes a and and returns a . + The Func that takes a and and returns a . @@ -344,11 +339,6 @@ To be added. - - - Starts a database transaction. - - Starts a database transaction. @@ -864,7 +854,7 @@ Changes the SQL Server password for the user indicated in the connection string to the supplied new password. - When you are using SQL Server on Windows Server, developers can take advantage of functionality that lets the client application supply both the current and a new password in order to change the existing password. Applications can implement functionality such as prompting the user for a new password during initial login if the old one has expired, and this operation can be completed without administrator intervention. The method changes the SQL Server password for the user indicated in the supplied connectionString parameter to the value supplied in the 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, nor returned to, the SQL Server connection pool. + When you are using SQL Server on Windows Server, developers can take advantage of functionality that lets the client application supply both the current and a new password in order to change the existing password. Applications can implement functionality such as prompting the user for a new password during initial login if the old one has expired, and this operation can be completed without administrator intervention. This method changes the SQL Server password for the user indicated in the supplied connectionString parameter to the value supplied in the 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, nor returned to, the SQL Server connection pool. @@ -1214,28 +1204,28 @@ Keyword - Default - Description + Default + Description - Addr + Addr N/A Synonym of Data Source. - Address + Address N/A Synonym of Data Source. - App + App N/A Synonym of Application Name. - + Application Intent or ApplicationIntent - + ReadWrite @@ -1247,7 +1237,7 @@ - Application Name + Application Name N/A @@ -1259,9 +1249,9 @@ - + AttachDBFilename or Extended Properties or Initial File Name - + N/A @@ -1291,7 +1281,7 @@ - Attestation Protocol + Attestation Protocol NotSpecified @@ -1311,7 +1301,7 @@ - Authentication + Authentication N/A @@ -1337,14 +1327,14 @@ - Column Encryption Setting + Column Encryption Setting disabled Enables or disables Always Encrypted functionality for the connection. Supported values are: enabled and disabled - Command Timeout + Command Timeout 30 @@ -1356,9 +1346,9 @@ - + Connect Retry Count or ConnectRetryCount - + 1 @@ -1373,9 +1363,9 @@ - + Connect Retry Interval or ConnectRetryInterval - + 10 @@ -1387,9 +1377,9 @@ - + Connect Timeout or Connection Timeout or Timeout - + 15 @@ -1404,9 +1394,9 @@ - + Current Language or Language - + N/A @@ -1418,9 +1408,9 @@ - + Data Source or Server or Address or Addr or Network Address - + N/A @@ -1483,12 +1473,12 @@ - Enclave Attestation Url + Enclave Attestation Url N/A Gets or sets the enclave attestation URL to be used with enclave based Always Encrypted. - Encrypt + Encrypt true in 4.0 and above

false in 3.x and below @@ -1511,14 +1501,14 @@
- Enlist + Enlist 'true' true indicates that the SQL Server connection pooler automatically enlists the connection in the creation thread's current transaction context. - Failover Partner + Failover Partner N/A @@ -1539,36 +1529,36 @@ - + Failover Partner SPN or FailoverPartnerSPN - + N/A The SPN for the failover partner. The default value is an empty string, which causes SqlClient to use the default, driver-generated SPN. (Only available in v5.0+) - + Host Name In Certificate or HostNameInCertificate - + N/A The host name to use when validating the server certificate. When not specified, the server name from the Data Source is used for certificate validation. (Only available in v5.0+) - + Server Certificate or ServerCertificate - + N/A The path to a certificate file to match against the SQL Server TLS/SSL certificate. The accepted certificate formats are PEM, DER, and CER. If specified, the SQL Server certificate is checked by verifying if the ServerCertificate provided is an exact match. (Only available in v5.1+) - + Initial Catalog or Database - + N/A @@ -1580,9 +1570,9 @@ - + Integrated Security or Trusted_Connection - + false @@ -1600,9 +1590,9 @@ - + IP Address Preference or IPAddressPreference - + IPv4First @@ -1616,9 +1606,9 @@ - + Load Balance Timeout or Connection Lifetime - + 0 @@ -1630,7 +1620,7 @@ - Max Pool Size + Max Pool Size 100 @@ -1642,7 +1632,7 @@ - Min Pool Size + Min Pool Size 0 @@ -1657,9 +1647,9 @@ - + Multiple Active Result Sets or MultipleActiveResultSets - + false @@ -1674,9 +1664,9 @@ - + Multi Subnet Failover or MultiSubnetFailover - + false @@ -1691,9 +1681,9 @@ - + Network Library or Network or Net - + N/A @@ -1718,7 +1708,7 @@ - Packet Size + Packet Size 8000 @@ -1730,9 +1720,9 @@ - + Password or PWD - + N/A @@ -1744,9 +1734,9 @@ - + Persist Security Info or PersistSecurityInfo - + false @@ -1761,16 +1751,16 @@ - + Pool Blocking Period or PoolBlockingPeriod - + Auto Sets the blocking period behavior for a connection pool. See property for details. - Pooling + Pooling true @@ -1785,14 +1775,14 @@ - Replication + Replication false true if replication is supported using the connection. - + Server SPN or ServerSPN - + N/A @@ -1801,7 +1791,7 @@ - Transaction Binding + Transaction Binding Implicit Unbind @@ -1826,9 +1816,9 @@ - + Transparent Network IP Resolution or TransparentNetworkIPResolution - + See description. @@ -1873,16 +1863,16 @@ - + Trust Server Certificate or TrustServerCertificate - + false When set to true, TLS 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. - Type System Version + Type System Version N/A @@ -1906,9 +1896,9 @@ - + User ID or UID or User - + N/A @@ -1920,16 +1910,16 @@ - User Instance + 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. @@ -2121,7 +2111,7 @@ - Persist Security Info = true is required to get the value of the object with . The default value of is null. An exception will be raised: + Persist Security Info = true is required to get the value of the object with . The default value of is null. An exception will be raised: @@ -2139,17 +2129,6 @@ - - - To be added. - - - To be added. - - - To be added. - - Gets the name of the current database or the database to be used after a connection is opened. @@ -2158,7 +2137,7 @@ 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. - The 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. + The 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. @@ -2289,7 +2268,7 @@ - You can use the 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. + You can use the method to enlist in a distributed transaction. Because it enlists a connection in a instance, takes advantage of functionality available in the namespace for managing distributed transactions, making it preferable to for this purpose. For more information, see 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 . @@ -2304,7 +2283,7 @@ Enlists in the specified transaction as a distributed transaction.
- You can use the 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. + You can use the method to enlist in a distributed transaction. Because it enlists a connection in a instance, takes advantage of functionality available in the namespace for managing distributed transactions, making it preferable to , which uses a object (from namespace). 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. @@ -2326,17 +2305,9 @@
- - - Returns schema information for the data source of this . - - - If you attempt to retrieve schema information for more than one versioned stored procedure, the schema for the latest one only is returned. - - - Returns schema information for the data source of this . For more information about scheme, see [SQL Server Schema Collections](/sql/connect/ado-net/sql-server-schema-collections). + Returns schema information for the data source of this . For more information about scheme, see SQL Server Schema Collections. A that contains schema information. @@ -2654,7 +2625,7 @@ is specified as null. - + @@ -2696,7 +2667,7 @@ 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. - 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. + 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. @@ -2776,7 +2747,7 @@ 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. - 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. + 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. @@ -2845,10 +2816,10 @@ - After calling , must return until the returned is completed. Then, if the connection was successful, must return . If the connection fails, must return . + After calling , 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. + 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. @@ -3005,7 +2976,6 @@ - ## Remarks You must set the value for this property before opening the connection to take effect. @@ -3018,10 +2988,10 @@ Create a by using one of the following static methods of the class: - - - - + + + + @@ -3210,7 +3180,7 @@ The version of the instance of SQL Server. - The version is of the form ##.##.####, where the first two digits are the major version, the next two digits are the minor version, and the last four digits are the release version. The string is of the form major.minor.build, where major and minor are exactly two digits and build is exactly four digits. was called while the returned Task was not completed and the connection was not opened after a call to . + The version is of the form ##.##.####, where the first two digits are the major version, the next two digits are the minor version, and the last four digits are the release version. The string is of the form major.minor.build, where major and minor are exactly two digits and build is exactly four digits. was called while the returned Task was not completed and the connection was not opened after a call to . @@ -3273,11 +3243,6 @@ Returns an enumeration indicating the state of the . Closing and reopening the connection will refresh the value of . - - - Occurs when the state of the connection changes. - - When set to , enables statistics gathering for the current connection. @@ -3289,39 +3254,6 @@ Enabling statistics gathering has a minor, but measurable effect on performance and therefore should be enabled only when it is required. - - - Begins a database transaction. - - - An object that represents the new transaction. - - - Once the transaction has completed, you must explicitly commit or roll back the transaction by using the or method. - - - - - One of the values. - - - Begins a database transaction with the specified value. - - - An object that represents the new transaction. - - - Once the transaction has completed, you must explicitly commit or roll back the transaction by using the or method. - - - - - Creates and returns a Command object that is associated with the connection. - - - A Command object that is associated with the connection. - - Creates a new object that is a copy of the current instance. diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptOption.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptOption.xml index d550f8d916..7a0dc7b54e 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptOption.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptOption.xml @@ -5,7 +5,7 @@ These options are used to control encryption behavior of the communication between the server and the client. - Implicit conversions have been added to maintain backwards compatibility with boolean behavior for the property. When converting from a boolean, a value of converts to and a value of converts to . When converting to a boolean, , , and convert to true and converts . + Implicit conversions have been added to maintain backwards compatibility with boolean behavior for the property. When converting from a boolean, a value of converts to and a value of converts to . When converting to a boolean, , , and convert to and converts . diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionOverrides.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionOverrides.xml index 612f0a3cba..06549e7e68 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionOverrides.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionOverrides.xml @@ -15,11 +15,11 @@ - Disable transient fault handling during the initial SqlConnection Open attempt. + Disable transient fault handling during the initial attempt. 1 - \ No newline at end of file + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlCredential.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlCredential.xml index 6e839a6019..686c0fb6e1 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlCredential.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlCredential.xml @@ -2,11 +2,11 @@ - provides a more secure way to specify the password for a login attempt using SQL Server Authentication. is comprised of a user id and a password that will be used for SQL Server Authentication. The password in a object is of type . cannot be inherited. Windows Authentication ( ) remains the most secure way to log in to a SQL Server database. + provides a more secure way to specify the password for a login attempt using SQL Server Authentication. is comprised of a user id and a password that will be used for SQL Server Authentication. The password in a object is of type . cannot be inherited. Windows Authentication (Integrated Security = true) remains the most secure way to log in to a SQL Server database. - Use to get or set a connection's object. Use to change the password for a object. For information on how a object affects connection pool behavior, see SQL Server Connection Pooling (ADO.NET). + Use to get or set a connection's object. Use to change the password for a object. For information on how a object affects connection pool behavior, see SQL Server Connection Pooling (ADO.NET). An exception will be raised if a non-null object is used in a connection with any of the following connection string keywords: @@ -19,11 +19,10 @@ - The following sample connects to a SQL Server database using : + The following sample connects to a SQL Server database using : change connection string in the APP.CONFIG file - <!-- --> <connectionStrings> <add name="MyConnString" connectionString="Initial Catalog=myDB;Server=myServer" providerName="Microsoft.Data.SqlClient" /> </connectionStrings> @@ -61,7 +60,7 @@ Creates an object of type . - The constructor does not accept null parameters. A value is allowed. An attempt to pass a null parameter in the constructor will raise an exception. + The constructor does not accept null parameters. An string.Empty value is allowed. An attempt to pass a null parameter in the constructor will raise an exception. Overview of the SqlClient driver diff --git a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs index 75b9e2905a..bdb54fc320 100644 --- a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs +++ b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs @@ -865,6 +865,7 @@ public void RegisterColumnEncryptionKeyStoreProvidersOnConnection(System.Collect [System.ComponentModel.DesignerSerializationVisibilityAttribute(0)] internal string SQLDNSCachingSupportedStateBeforeRedirect { get { throw null; } } + /// object System.ICloneable.Clone() { throw null; } /// [System.ComponentModel.DesignerSerializationVisibilityAttribute(0)] diff --git a/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs b/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs index 2a581480d5..9e8e60483c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs +++ b/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs @@ -775,6 +775,7 @@ public SqlConnection(string connectionString, Microsoft.Data.SqlClient.SqlCreden /// [System.ComponentModel.DesignerSerializationVisibilityAttribute(0)] public System.Guid ClientConnectionId { get { throw null; } } + /// object System.ICloneable.Clone() { throw null; } /// [System.ComponentModel.DefaultValueAttribute(null)] diff --git a/src/Microsoft.Data.SqlClient/ref/Microsoft.Data.SqlClient.Batch.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/ref/Microsoft.Data.SqlClient.Batch.NetCoreApp.cs index c49273bbf8..a693a7f9c1 100644 --- a/src/Microsoft.Data.SqlClient/ref/Microsoft.Data.SqlClient.Batch.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/ref/Microsoft.Data.SqlClient.Batch.NetCoreApp.cs @@ -11,19 +11,19 @@ public partial class SqlBatchCommand public Microsoft.Data.SqlClient.SqlCommandColumnEncryptionSetting ColumnEncryptionSetting { get { throw null; } set { } } } - /// + /// public partial class SqlConnection { - /// + /// public override bool CanCreateBatch { get { throw null; } } - /// + /// protected override System.Data.Common.DbBatch CreateDbBatch() => throw null; } - /// + /// public partial class SqlException { - /// + /// protected override System.Data.Common.DbBatchCommand DbBatchCommand => throw null; } } From 7bb429dddedaebb6b24ab0e2c839fa1f3391da42 Mon Sep 17 00:00:00 2001 From: Ben Russell Date: Thu, 12 Sep 2024 15:33:09 -0500 Subject: [PATCH 3/4] Tabs to spaces --- .../SqlCommandBuilder.xml | 876 +++--- .../SqlCommandColumnEncryptionSetting.xml | 58 +- .../SqlConfigurableRetryFactory.xml | 154 +- .../SqlConnection.xml | 2710 ++++++++--------- .../SqlConnectionAttestationProtocol.xml | 78 +- .../SqlConnectionColumnEncryptionSetting.xml | 36 +- .../SqlConnectionEncryptOption.xml | 174 +- .../SqlConnectionIPAddressPreference.xml | 72 +- .../SqlConnectionOverrides.xml | 46 +- .../SqlCredential.xml | 92 +- 10 files changed, 2148 insertions(+), 2148 deletions(-) diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlCommandBuilder.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlCommandBuilder.xml index b2b71ad4ed..5cf4867488 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlCommandBuilder.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlCommandBuilder.xml @@ -1,28 +1,28 @@  - - - - Automatically generates single-table commands that are used to reconcile changes made to a with the associated SQL Server database. This class cannot be inherited. - - - - The does not automatically generate the Transact-SQL statements required to reconcile changes made to a with the associated instance of SQL Server. However, you can create a object to automatically generate Transact-SQL statements for single-table updates if you set the property of the . Then, any additional Transact-SQL statements that you do not set are generated by the . - - - The registers itself as a listener for events whenever you set the property. You can only associate one or object with each other at one time. - - - To generate INSERT, UPDATE, or DELETE statements, the uses the property to retrieve a required set of metadata automatically. If you change the after the metadata has been retrieved, such as after the first update, you should call the method to update the metadata. - - - The must also return at least one primary key or unique column. If none are present, an exception is generated, and the commands are not generated. - - - The also uses the , , and properties referenced by the . The user should call if one or more of these properties are modified, or if the itself is replaced. Otherwise the , , and properties retain their previous values. - - - If you call , the is disassociated from the , and the generated commands are no longer used. - + + + + Automatically generates single-table commands that are used to reconcile changes made to a with the associated SQL Server database. This class cannot be inherited. + + + + The does not automatically generate the Transact-SQL statements required to reconcile changes made to a with the associated instance of SQL Server. However, you can create a object to automatically generate Transact-SQL statements for single-table updates if you set the property of the . Then, any additional Transact-SQL statements that you do not set are generated by the . + + + The registers itself as a listener for events whenever you set the property. You can only associate one or object with each other at one time. + + + To generate INSERT, UPDATE, or DELETE statements, the uses the property to retrieve a required set of metadata automatically. If you change the after the metadata has been retrieved, such as after the first update, you should call the method to update the metadata. + + + The must also return at least one primary key or unique column. If none are present, an exception is generated, and the commands are not generated. + + + The also uses the , , and properties referenced by the . The user should call if one or more of these properties are modified, or if the itself is replaced. Otherwise the , , and properties retain their previous values. + + + If you call , the is disassociated from the , and the generated commands are no longer used. + @@ -73,161 +73,161 @@ } - - - - Initializes a new instance of the class. - - - - - The name of the . - - - Initializes a new instance of the class with the associated object. - - - - The registers itself as a listener for events that are generated by the specified in this property. - - - When you create a new instance of , any existing associated with this is released. - - - - - - To be added. - - - To be added. - - - To be added. - - - To be added. - - - To be added. - - - To be added. - - - - - Sets or gets the for an instance of the class. - - - A object. - - - - - Sets or gets a string used as the catalog separator for an instance of the class. - - - A string that indicates the catalog separator for use with an instance of the class. - - - - - Gets or sets a object for which Transact-SQL statements are automatically generated. - - - A object. - - - - The registers itself as a listener for events that are generated by the specified in this property. - - - When you create a new instance of , any existing associated with this is released. - - - - - - The referencing the stored procedure from which the parameter information is to be derived. The derived parameters are added to the collection of the . - - - Retrieves parameter information from the stored procedure specified in the and populates the collection of the specified object. - - - - DeriveParameters overwrites any existing parameter information for the . - - - DeriveParameters requires an additional call to the database to obtain the information. If the parameter information is known in advance, it is more efficient to populate the parameters collection by setting the information explicitly. - - - You can only use DeriveParameters with stored procedures. You cannot use DeriveParameters with extended stored procedures. You cannot use DeriveParameters to populate the with arbitrary Transact-SQL statements, such as a parameterized SELECT statement. - - - For more information, see Configuring parameters. - - - - The command text is not a valid stored procedure name. - - - - - To be added. - - - To be added. - - - To be added. - - - - - Gets the automatically generated object required to perform deletions on the database. - - - The automatically generated object required to perform deletions. - - - - An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. - - - You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - - - After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The SQL statements are first generated when the application calls either or . - - - For more information, see Generating Commands with CommandBuilders. - - - - - - If , generate parameter names matching column names if possible. If , generate @p1, @p2, and so on. - - - Gets the automatically generated object that is required to perform deletions on the database. - - - The automatically generated object that is required to perform deletions. - - - - An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. - - - You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - - - After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The SQL statements are first generated when the application calls either or . - - - The default behavior, when generating parameter names, is to use @p1, @p2, and so on for the various parameters. Passing for the parameter lets you force the command builder to generate parameters based on the column names instead. This succeeds only if the following conditions are met: - + + + + Initializes a new instance of the class. + + + + + The name of the . + + + Initializes a new instance of the class with the associated object. + + + + The registers itself as a listener for events that are generated by the specified in this property. + + + When you create a new instance of , any existing associated with this is released. + + + + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + + + Sets or gets the for an instance of the class. + + + A object. + + + + + Sets or gets a string used as the catalog separator for an instance of the class. + + + A string that indicates the catalog separator for use with an instance of the class. + + + + + Gets or sets a object for which Transact-SQL statements are automatically generated. + + + A object. + + + + The registers itself as a listener for events that are generated by the specified in this property. + + + When you create a new instance of , any existing associated with this is released. + + + + + + The referencing the stored procedure from which the parameter information is to be derived. The derived parameters are added to the collection of the . + + + Retrieves parameter information from the stored procedure specified in the and populates the collection of the specified object. + + + + DeriveParameters overwrites any existing parameter information for the . + + + DeriveParameters requires an additional call to the database to obtain the information. If the parameter information is known in advance, it is more efficient to populate the parameters collection by setting the information explicitly. + + + You can only use DeriveParameters with stored procedures. You cannot use DeriveParameters with extended stored procedures. You cannot use DeriveParameters to populate the with arbitrary Transact-SQL statements, such as a parameterized SELECT statement. + + + For more information, see Configuring parameters. + + + + The command text is not a valid stored procedure name. + + + + + To be added. + + + To be added. + + + To be added. + + + + + Gets the automatically generated object required to perform deletions on the database. + + + The automatically generated object required to perform deletions. + + + + An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. + + + You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . + + + After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The SQL statements are first generated when the application calls either or . + + + For more information, see Generating Commands with CommandBuilders. + + + + + + If , generate parameter names matching column names if possible. If , generate @p1, @p2, and so on. + + + Gets the automatically generated object that is required to perform deletions on the database. + + + The automatically generated object that is required to perform deletions. + + + + An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. + + + You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . + + + After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The SQL statements are first generated when the application calls either or . + + + The default behavior, when generating parameter names, is to use @p1, @p2, and so on for the various parameters. Passing for the parameter lets you force the command builder to generate parameters based on the column names instead. This succeeds only if the following conditions are met: + The returned from the GetSchema method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name. @@ -239,56 +239,56 @@ A returned from the GetSchema method call and found in the collection is specified. - - For more information, see Generating Commands with CommandBuilders. - - - - - - Gets the automatically generated object required to perform insertions on the database. - - - The automatically generated object required to perform insertions. - - - - An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. - - - You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - - - After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . - - - For more information, see Generating Commands with CommandBuilders. - - - - - - If , generate parameter names matching column names if possible. If , generate @p1, @p2, and so on. - - - Gets the automatically generated object that is required to perform insertions on the database. - - - The automatically generated object that is required to perform insertions. - - - - An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. - - - You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - - - After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . - - - The default behavior, when generating parameter names, is to use @p1, @p2, and so on for the various parameters. Passing for the parameter lets you force the command builder to generate parameters based on the column names instead. This succeeds only if the following conditions are met: - + + For more information, see Generating Commands with CommandBuilders. + + + + + + Gets the automatically generated object required to perform insertions on the database. + + + The automatically generated object required to perform insertions. + + + + An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. + + + You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . + + + After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . + + + For more information, see Generating Commands with CommandBuilders. + + + + + + If , generate parameter names matching column names if possible. If , generate @p1, @p2, and so on. + + + Gets the automatically generated object that is required to perform insertions on the database. + + + The automatically generated object that is required to perform insertions. + + + + An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. + + + You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . + + + After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . + + + The default behavior, when generating parameter names, is to use @p1, @p2, and so on for the various parameters. Passing for the parameter lets you force the command builder to generate parameters based on the column names instead. This succeeds only if the following conditions are met: + The returned from the GetSchema method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name. @@ -300,112 +300,112 @@ A returned from the GetSchema method call and found in the collection is specified. - - For more information, see Generating Commands with CommandBuilders. - - - - - - To be added. - - - To be added. - - - To be added. - - - To be added. - - - - - To be added. - - - To be added. - - - To be added. - - - To be added. - - - - - To be added. - - - To be added. - - - To be added. - - - To be added. - - - - - To be added. - - - To be added. - - - To be added. - - - To be added. - - - - - Gets the automatically generated object required to perform updates on the database. - - - The automatically generated object that is required to perform updates. - - - - An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. - - - You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - - - After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . - - - For more information, see Generating Commands with CommandBuilders. - - - - - - If , generate parameter names matching column names if possible. If , generate @p1, @p2, and so on. - - - Gets the automatically generated object required to perform updates on the database. - - - The automatically generated object required to perform updates. - - - - An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. - - - You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . - - - After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . - - - The default behavior, when generating parameter names, is to use @p1, @p2, and so on for the various parameters. Passing for the parameter lets you force the command builder to generate parameters based on the column names instead. This succeeds only if the following conditions are met: - + + For more information, see Generating Commands with CommandBuilders. + + + + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + + + Gets the automatically generated object required to perform updates on the database. + + + The automatically generated object that is required to perform updates. + + + + An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. + + + You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . + + + After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . + + + For more information, see Generating Commands with CommandBuilders. + + + + + + If , generate parameter names matching column names if possible. If , generate @p1, @p2, and so on. + + + Gets the automatically generated object required to perform updates on the database. + + + The automatically generated object required to perform updates. + + + + An application can use the method for informational or troubleshooting purposes because it returns the object to be executed. + + + You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the . + + + After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or . + + + The default behavior, when generating parameter names, is to use @p1, @p2, and so on for the various parameters. Passing for the parameter lets you force the command builder to generate parameters based on the column names instead. This succeeds only if the following conditions are met: + The returned from the GetSchema method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name. @@ -417,114 +417,114 @@ A returned from the GetSchema method call and found in the collection is specified. - - For more information, see Generating Commands with CommandBuilders. - - - - - - To be added. - - - To be added. - - - To be added. - - - To be added. - - - - - To be added. - - - To be added. - - - To be added. - - - To be added. - - - - - Gets or sets the starting character or characters to use when specifying SQL Server database objects, such as tables or columns, whose names contain characters such as spaces or reserved tokens. - - - The starting character or characters to use. The default is an empty string. - - + + For more information, see Generating Commands with CommandBuilders. + + + + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + + + Gets or sets the starting character or characters to use when specifying SQL Server database objects, such as tables or columns, whose names contain characters such as spaces or reserved tokens. + + + The starting character or characters to use. The default is an empty string. + + Although you cannot change the or properties after an insert, update, or delete command has been generated, you can change their settings after calling the Update method of a DataAdapter. - - - This property cannot be changed after an INSERT, UPDATE, or DELETE command has been generated. - - - - - Gets or sets the ending character or characters to use when specifying SQL Server database objects, such as tables or columns, whose names contain characters such as spaces or reserved tokens. - - - The ending character or characters to use. The default is an empty string. - - + + + This property cannot be changed after an INSERT, UPDATE, or DELETE command has been generated. + + + + + Gets or sets the ending character or characters to use when specifying SQL Server database objects, such as tables or columns, whose names contain characters such as spaces or reserved tokens. + + + The ending character or characters to use. The default is an empty string. + + Although you cannot change the or properties after an insert, update, or delete operation has been generated, you can change their settings after calling the Update method of a DataAdapter. - - - This property cannot be changed after an insert, update, or delete command has been generated. - - - - - Gets or sets the character to be used for the separator between the schema identifier and any other identifiers. - - - The character to be used as the schema separator. - - - + + + This property cannot be changed after an insert, update, or delete command has been generated. + + + + + Gets or sets the character to be used for the separator between the schema identifier and any other identifiers. + + + The character to be used as the schema separator. + + + Generally, database servers indicate the schema for a identifier by separating the schema name from the identifier with some character. For example, SQL Server uses a period, creating complete identifiers such as Person.CustomerName, where "Person" is the schema name and "CustomerName" is the identifier. Setting this property lets developers modify this behavior. - - - - - - To be added. - - - To be added. - - - To be added. - - - - - The identifier that will have its embedded quotes removed. - - - Given a quoted identifier, returns the correct unquoted form of that identifier. This includes correctly unescaping any embedded quotes in the identifier. - - - The unquoted identifier, with embedded quotes properly unescaped. - - - Connecting and Retrieving Data in ADO.NET - - - Using the .NET Framework Data Provider for SQL Server - - - Overview of the SqlClient driver - - - + + + + + + To be added. + + + To be added. + + + To be added. + + + + + The identifier that will have its embedded quotes removed. + + + Given a quoted identifier, returns the correct unquoted form of that identifier. This includes correctly unescaping any embedded quotes in the identifier. + + + The unquoted identifier, with embedded quotes properly unescaped. + + + Connecting and Retrieving Data in ADO.NET + + + Using the .NET Framework Data Provider for SQL Server + + + Overview of the SqlClient driver + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlCommandColumnEncryptionSetting.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlCommandColumnEncryptionSetting.xml index e6ac404675..ddd254827a 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlCommandColumnEncryptionSetting.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlCommandColumnEncryptionSetting.xml @@ -1,10 +1,10 @@  - - - - Note that these settings cannot be used to bypass encryption and gain access to plaintext data. For details, see Always Encrypted (Database Engine). - - + + + + Note that these settings cannot be used to bypass encryption and gain access to plaintext data. For details, see Always Encrypted (Database Engine). + + If Always Encrypted is disabled for a query and the query has parameters that need to be encrypted (parameters that correspond to encrypted columns), the query will fail. @@ -13,27 +13,27 @@ If Always Encrypted is disabled for a query and the query returns results from encrypted columns, the query will return encrypted values. The encrypted values will have the varbinary datatype. - - - - - Specifies the connection does not use Always Encrypted. Should be used if no queries sent over the connection access encrypted columns. - - - - - Enables Always Encrypted for the query. - - - - - Specifies that only the results of the command should be processed by the Always Encrypted routine in the driver. Use this value when the command has no parameters that require encryption. - - - - - Specifies that the command should default to the Always Encrypted setting in the connection string. - - - + + + + + Specifies the connection does not use Always Encrypted. Should be used if no queries sent over the connection access encrypted columns. + + + + + Enables Always Encrypted for the query. + + + + + Specifies that only the results of the command should be processed by the Always Encrypted routine in the driver. Use this value when the command has no parameters that require encryption. + + + + + Specifies that the command should default to the Always Encrypted setting in the connection string. + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConfigurableRetryFactory.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConfigurableRetryFactory.xml index 6b3a484460..c8c5513ea5 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConfigurableRetryFactory.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConfigurableRetryFactory.xml @@ -1,13 +1,13 @@  - - - - Provides different retry logic providers with a common list of transient errors. - - - - The following table shows the inner transient error list. - + + + + Provides different retry logic providers with a common list of transient errors. + + + + The following table shows the inner transient error list. + Error Number @@ -114,28 +114,28 @@ - - - - - An object of containing the configuration for the object. - - - Provides an exponential time interval retry logic provider. - - - A object. - - + + + + + An object of containing the configuration for the object. + + + Provides an exponential time interval retry logic provider. + + + A object. + + The inner enumerator includes randomization to prevent multiple instances of the client from performing subsequent retry attempts at the same time. - - - If the parameter was null. - - - If at least one of the following conditions occurs: + + + If the parameter was null. + + + If at least one of the following conditions occurs: is less than 1 or bigger than 60. @@ -153,27 +153,27 @@ is not less than . - - - - - An object of containing the configuration for the object. - - - Provides an incremental time interval retry logic provider. - - - A object. - - + + + + + An object of containing the configuration for the object. + + + Provides an incremental time interval retry logic provider. + + + A object. + + The inner enumerator includes randomization to prevent multiple instances of the client from performing subsequent retry attempts at the same time. - - - If the parameter was null. - - + + + If the parameter was null. + + If at least one of the following conditions occurs: @@ -192,27 +192,27 @@ is not less than . - - - - - An object of containing the configuration for the object. - - - Provides a fixed interval time retry logic provider. - - - A object. - - + + + + + An object of containing the configuration for the object. + + + Provides a fixed interval time retry logic provider. + + + A object. + + The inner enumerator includes randomization to prevent multiple instances of the client from performing subsequent retry attempts at the same time. - - - If the `retryLogicOption` parameter was null. - - + + + If the `retryLogicOption` parameter was null. + + If at least one of the following conditions occurs: @@ -231,20 +231,20 @@ is not less than . - - - - - Provides a non-retryable provider with a that returns . - - - A object. - - + + + + + Provides a non-retryable provider with a that returns . + + + A object. + + The returned provider of this function performs a single execution without any retry logic. - - - + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml index fda08fea7b..2bacd40540 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml @@ -1,51 +1,51 @@  - - - - Represents a connection to a SQL Server database. This class cannot be inherited. - - - - A 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 or . and 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. - - - 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). - - - 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. - - - Using connection As New SqlConnection(connectionString) - connection.Open() - ' Do work here; connection closed on following line. - End Using - - - using (SqlConnection connection = new SqlConnection(connectionString)) - { - connection.Open(); - // Do work here; connection closed on following line. - } - - - 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). - - - 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) to modify security policy at the machine, user, and enterprise levels. For more information, see Security in .NET. For an example demonstrating how to use security demands, see Code Access Security and ADO.NET. - For more information about handling warning and informational messages from the server, see Connection Events. For more information about SQL Server engine errors and error messages, see Database Engine Events and Errors. - - - 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. - + + + + Represents a connection to a SQL Server database. This class cannot be inherited. + + + + A 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 or . and 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. + + + 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). + + + 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. + + + Using connection As New SqlConnection(connectionString) + connection.Open() + ' Do work here; connection closed on following line. + End Using + + + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + // Do work here; connection closed on following line. + } + + + 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). + + + 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) to modify security policy at the machine, user, and enterprise levels. For more information, see Security in .NET. For an example demonstrating how to use security demands, see Code Access Security and ADO.NET. + For more information about handling warning and informational messages from the server, see Connection Events. For more information about SQL Server engine errors and error messages, see Database Engine Events and Errors. + + + 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. + @@ -81,40 +81,40 @@ } - - - - Initializes a new instance of the class. - - - - When a new instance of 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. - + + + + Initializes a new instance of the class. + + + + When a new instance of 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. + @@ -156,43 +156,43 @@ } - - - - 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. - - - - When a new instance of 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. - + + + + 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. + + + + When a new instance of 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. + @@ -237,43 +237,43 @@ } - - The supplied connection string argument failed validation. - - - - - A connection string that does not use any of the following connection string keywords: Integrated Security = true, UserId, or Password; or that does not use ConnectionContext = true. - - - A object. If is null, is functionally equivalent to . - - - Initializes a new instance of the class given a connection string, that does not use Integrated Security = true and a object that contains the user ID and password. - - - The supplied arguments failed validation, including validation. - - - - - Gets or sets the access token for the connection. - - - The access token for the connection. - - - The AccessToken is a part of the connection pool key. Care should be taken when using this property to manage your own access token. The application is responsible for knowing when the token expires and connections from the pool should no longer be used. If you set a minimum pool size > 0 along with AccessToken, you must call after the access token expires to ensure the connection pool doesn't maintain those connections indefinitely. - - - - - Gets or sets the access token callback for the connection. - - - The Func that takes a and and returns a . - - + + The supplied connection string argument failed validation. + + + + + A connection string that does not use any of the following connection string keywords: Integrated Security = true, UserId, or Password; or that does not use ConnectionContext = true. + + + A object. If is null, is functionally equivalent to . + + + Initializes a new instance of the class given a connection string, that does not use Integrated Security = true and a object that contains the user ID and password. + + + The supplied arguments failed validation, including validation. + + + + + Gets or sets the access token for the connection. + + + The access token for the connection. + + + The AccessToken is a part of the connection pool key. Care should be taken when using this property to manage your own access token. The application is responsible for knowing when the token expires and connections from the pool should no longer be used. If you set a minimum pool size > 0 along with AccessToken, you must call after the access token expires to ensure the connection pool doesn't maintain those connections indefinitely. + + + + + Gets or sets the access token callback for the connection. + + + The Func that takes a and and returns a . + + The following example demonstrates how to define and set an . @@ -321,47 +321,47 @@ } - - The is combined with other conflicting authentication configurations. - - - - - To be added. - - - To be added. - - - To be added. - - - To be added. - - - - - Starts a database transaction. - - - An object representing the new transaction. - - - - This command maps to the SQL Server implementation of BEGIN TRANSACTION.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. - - - 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. - - - 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 . - - - When your query returns a large amount of data and calls , 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). - + + The is combined with other conflicting authentication configurations. + + + + + To be added. + + + To be added. + + + To be added. + + + To be added. + + + + + Starts a database transaction. + + + An object representing the new transaction. + + + + This command maps to the SQL Server implementation of BEGIN TRANSACTION.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. + + + 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. + + + 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 . + + + When your query returns a large amount of data and calls , 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). + @@ -439,36 +439,36 @@ } - - Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). - - - Parallel transactions are not supported. - - - - - The isolation level under which the transaction should run. - - - Starts a database transaction with the specified isolation level. - - - An object representing the new transaction. - - - - This command maps to the SQL Server implementation of BEGIN TRANSACTION. 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. - - - 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. - - - For more information on SQL Server transactions, see Transactions (Transact-SQL). - - - When your query returns a large amount of data and calls , 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. - + + Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). + + + Parallel transactions are not supported. + + + + + The isolation level under which the transaction should run. + + + Starts a database transaction with the specified isolation level. + + + An object representing the new transaction. + + + + This command maps to the SQL Server implementation of BEGIN TRANSACTION. 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. + + + 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. + + + For more information on SQL Server transactions, see Transactions (Transact-SQL). + + + When your query returns a large amount of data and calls , 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. + @@ -542,30 +542,30 @@ } - - Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). - - - Parallel transactions are not supported. - - - - - The name of the transaction. - - - Starts a database transaction with the specified transaction name. - - - An object representing the new transaction. - - - - This command maps to the SQL Server implementation of BEGIN TRANSACTION. The length of the parameter must not exceed 32 characters; otherwise an exception will be thrown. The value in the parameter can be used in later calls to 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 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). - - - When your query returns a large amount of data and calls , 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. - + + Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). + + + Parallel transactions are not supported. + + + + + The name of the transaction. + + + Starts a database transaction with the specified transaction name. + + + An object representing the new transaction. + + + + This command maps to the SQL Server implementation of BEGIN TRANSACTION. The length of the parameter must not exceed 32 characters; otherwise an exception will be thrown. The value in the parameter can be used in later calls to 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 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). + + + When your query returns a large amount of data and calls , 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. + @@ -644,39 +644,39 @@ } - - Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). - - - Parallel transactions are not supported. - - - - - 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. - - - - This command maps to the SQL Server implementation of BEGIN TRANSACTION. The value in the parameter can be used in later calls to 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. - - - 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. - - - For more information on SQL Server transactions, see Transactions (Transact-SQL). - - - When your query returns a large amount of data and calls , 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. - + + Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). + + + Parallel transactions are not supported. + + + + + 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. + + + + This command maps to the SQL Server implementation of BEGIN TRANSACTION. The value in the parameter can be used in later calls to 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. + + + 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. + + + For more information on SQL Server transactions, see Transactions (Transact-SQL). + + + When your query returns a large amount of data and calls , 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. + @@ -754,32 +754,32 @@ } - - Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). - - - Parallel transactions are not supported. - - - - - Gets a value that indicates whether this instance supports the class. - - - if this instance supports the class; otherwise, . The default is . - - + + Parallel transactions are not allowed when using Multiple Active Result Sets (MARS). + + + Parallel transactions are not supported. + + + + + Gets a value that indicates whether this instance supports the class. + + + if this instance supports the class; otherwise, . The default is . + + ADO.net SQL provider implemented and overrides CanCreateBatch property to return . - - - - - The name of the database to use instead of the current database. - - - Changes the current database for an open . - - + + + + + The name of the database to use instead of the current database. + + + Changes the current database for an open . + + The value supplied in the parameter must be a valid database name. The parameter cannot contain a null value, an empty string, or a string with only blank characters. @@ -828,32 +828,32 @@ } - - The database name is not valid. - - - The connection is not open. - - - Cannot change the database. - - - - - Changes the SQL Server password. - - - - - 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 supplied new password. - - + + The database name is not valid. + + + The connection is not open. + + + Cannot change the database. + + + + + Changes the SQL Server password. + + + + + 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 supplied new password. + + When you are using SQL Server on Windows Server, developers can take advantage of functionality that lets the client application supply both the current and a new password in order to change the existing password. Applications can implement functionality such as prompting the user for a new password during initial login if the old one has expired, and this operation can be completed without administrator intervention. This method changes the SQL Server password for the user indicated in the supplied connectionString parameter to the value supplied in the 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, nor returned to, the SQL Server connection pool. @@ -861,24 +861,24 @@ The following is a simple example of changing a password: - class Program - { - static void Main(string[] args) - { - Microsoft.Data.SqlClient.SqlConnection.ChangePassword( - "Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password", - "new_password"); - } - } - + class Program + { + static void Main(string[] args) + { + Microsoft.Data.SqlClient.SqlConnection.ChangePassword( + "Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password", + "new_password"); + } + } + Module Module1 - Sub Main() - Microsoft.Data.SqlClient.SqlConnection.ChangePassword( - "Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password", - "new_password") - End Sub - End Module + Sub Main() + Microsoft.Data.SqlClient.SqlConnection.ChangePassword( + "Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password", + "new_password") + End Sub + End Module @@ -998,7 +998,7 @@ } - + The connection string includes the option to use integrated security. @@ -1007,25 +1007,25 @@ The exceeds 128 characters. - - - Either the or the parameter is null. - - - - - 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: Integrated Security = true, UserId, or Password ; or ContextConnection = true. - - - 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). - - - Changes the SQL Server password for the user indicated in the object. - - + + + Either the or the parameter is null. + + + + + 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: Integrated Security = true, UserId, or Password ; or ContextConnection = true. + + + 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). + + + Changes the SQL Server password for the user indicated in the object. + + The connection string contains any combination of UserId, Password, or Integrated Security=true. @@ -1040,66 +1040,66 @@ is an empty string. - - - One of the parameters (, , or ) is null. - - - - - Empties the connection pool. - - + + + One of the parameters (, , or ) is null. + + + + + 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. - - - - - The to be cleared from the pool. - - - Empties the connection pool associated with the specified connection. - - + + + + + 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 . If additional connections associated with 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. - - - - - 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 (Connectivity troubleshooting in SQL Server 2008 with the Connectivity Ring Buffer) for certain connection errors. If the connection ID is not in the connection ring buffer, you can assume a network error. - - - - - - Closes the connection to the database. This is the preferred method of closing any open connection. - - - - The method rolls back any pending transactions. It then releases the connection to the connection pool, or closes the connection if connection pooling is disabled. - - - 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 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. - - - 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). - - - 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. - + + + + + 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 (Connectivity troubleshooting in SQL Server 2008 with the Connectivity Ring Buffer) for certain connection errors. If the connection ID is not in the connection ring buffer, you can assume a network error. + + + + + + Closes the connection to the database. This is the preferred method of closing any open connection. + + + + The method rolls back any pending transactions. It then releases the connection to the connection pool, or closes the connection if connection pooling is disabled. + + + 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 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. + + + 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). + + + 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. + @@ -1142,118 +1142,118 @@ } - - The connection-level error that occurred while opening the connection. - - - - - 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. - - - - - 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. - - - For parameterized queries, SqlClient makes a roundtrip to SQL Server for parameter metadata, to see which parameter it needs to encrypt and how (which keys and algorithms should be used). If the application calls the same query multiple times, an extra roundtrip is made to the server each time, which degrades application performance. With ColumnEncryptionQueryMetadataCacheEnabled set to true, if the same query is called multiple times, the roundtrip to the server will be made only once. The cache has a non-configurable Max size parameter that is set to 2000 queries. - - - - - 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. - - - - - Gets the default wait time (in seconds) before terminating the attempt to execute a command and generating an error. The default is 30 seconds. - - - The time in seconds to wait for the command to execute. The default is 30 seconds. - - - You can set the default wait time by using the Command Timeout keyword in the connection string. A value of 0 indicates no limit (an attempt to execute a command will wait indefinitely). - - - - - 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. - - - - The 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. - - - "Persist Security Info=False;Integrated Security=true;Initial Catalog=Northwind;server=(local)" - - + + The connection-level error that occurred while opening the connection. + + + + + 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. + + + + + 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. + + + For parameterized queries, SqlClient makes a roundtrip to SQL Server for parameter metadata, to see which parameter it needs to encrypt and how (which keys and algorithms should be used). If the application calls the same query multiple times, an extra roundtrip is made to the server each time, which degrades application performance. With ColumnEncryptionQueryMetadataCacheEnabled set to true, if the same query is called multiple times, the roundtrip to the server will be made only once. The cache has a non-configurable Max size parameter that is set to 2000 queries. + + + + + 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. + + + + + Gets the default wait time (in seconds) before terminating the attempt to execute a command and generating an error. The default is 30 seconds. + + + The time in seconds to wait for the command to execute. The default is 30 seconds. + + + You can set the default wait time by using the Command Timeout keyword in the connection string. A value of 0 indicates no limit (an attempt to execute a command will wait indefinitely). + + + + + 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. + + + + The 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. + + + "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. 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. - - - + + + + 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 Intent or ApplicationIntent - - ReadWrite - + + 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. - - - - Application Name - N/A - + + + + Application Name + N/A + The name of the application. If no application name is provided, 'Framework Microsoft SqlClient Data Provider' when running on .NET Framework and 'Core Microsoft SqlClient Data Provider' otherwise. An application name can be 128 characters or fewer. - - - - + + + + AttachDBFilename or Extended Properties or Initial File Name - - N/A - + + 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. @@ -1278,12 +1278,12 @@ 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. - - - - Attestation Protocol - NotSpecified - + + + + Attestation Protocol + NotSpecified + Gets or sets the value of Attestation Protocol. @@ -1298,12 +1298,12 @@ HGS None (Only valid in v3.1 and v4.1+) - - - - Authentication - N/A - + + + + Authentication + N/A + The authentication method used for Connecting to SQL Database By Using Azure Active Directory Authentication. @@ -1324,33 +1324,33 @@ For additional information see Using Azure Active Directory authentication with SqlClient. - - - - Column Encryption Setting - disabled - - Enables or disables Always Encrypted functionality for the connection. Supported values are: enabled and disabled - - - - Command Timeout - 30 - + + + + Column Encryption Setting + disabled + + Enables or disables Always Encrypted functionality for the connection. Supported values are: enabled and disabled + + + + Command Timeout + 30 + The default wait time (in seconds) before terminating the attempt to execute a command and generating an error. Valid values are greater than or equal to 0 and less than or equal to 2147483647. - - - - - Connect Retry Count or ConnectRetryCount - - 1 - + + + + + Connect Retry Count or ConnectRetryCount + + 1 + Controls the number of reconnection attempts after the client identifies an idle connection failure. Valid values are 0 to 255. 0 means do not attempt to reconnect (disable connection resiliency). @@ -1360,28 +1360,28 @@ For additional information about idle connection resiliency, see .NET SqlConnection parameters for connection retry and Technical Article - Idle Connection Resiliency. - - - - + + + + Connect Retry Interval or ConnectRetryInterval - - 10 - + + 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 idle connection resiliency, see .NET SqlConnection parameters for connection retry and Technical Article - Idle Connection Resiliency. - - - - + + + + Connect Timeout or Connection Timeout or Timeout - - 15 - + + 15 + The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error. @@ -1391,28 +1391,28 @@ When opening a connection to a Azure SQL Database, set the connection timeout to 30 seconds. - - - - + + + + Current Language or Language - - N/A - + + N/A + Sets the language used for database server warning or error messages. The language name can be 128 characters or fewer. - - - - + + + + Data Source or Server or Address or Addr or Network Address - - N/A - + + 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 @@ -1470,20 +1470,20 @@ 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. - - - - Enclave Attestation Url - N/A - Gets or sets the enclave attestation URL to be used with enclave based Always Encrypted. - - - Encrypt - - true in 4.0 and above

- false in 3.x and below -
- + +
+ + Enclave Attestation Url + N/A + Gets or sets the enclave attestation URL to be used with enclave based Always Encrypted. + + + Encrypt + + true in 4.0 and above

+ false in 3.x and below +
+ Recognized values are: @@ -1495,22 +1495,22 @@ versions 5+: true / yes / mandatory, false / no / optional and strict. When true, TLS encryption is used for all data sent between the client and server if the server has a certificate installed. When strict, TDS 8.0 TLS encryption is used and the TrustServerCertificate setting is ignored and treated as false. For more information, see Connection String Syntax.
- + When Encrypt is mandatory or strict and TrustServerCertificate is false, the server name (or IP address) in a server's 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 - + + + + 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. @@ -1526,55 +1526,55 @@ 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. - - - - + + + + Failover Partner SPN or FailoverPartnerSPN - - N/A - + + N/A + The SPN for the failover partner. The default value is an empty string, which causes SqlClient to use the default, driver-generated SPN. (Only available in v5.0+) - - - - + + + + Host Name In Certificate or HostNameInCertificate - - N/A - - The host name to use when validating the server certificate. When not specified, the server name from the Data Source is used for certificate validation. (Only available in v5.0+) - - - - + + N/A + + The host name to use when validating the server certificate. When not specified, the server name from the Data Source is used for certificate validation. (Only available in v5.0+) + + + + Server Certificate or ServerCertificate - - N/A - - The path to a certificate file to match against the SQL Server TLS/SSL certificate. The accepted certificate formats are PEM, DER, and CER. If specified, the SQL Server certificate is checked by verifying if the ServerCertificate provided is an exact match. (Only available in v5.1+) - - - - + + N/A + + The path to a certificate file to match against the SQL Server TLS/SSL certificate. The accepted certificate formats are PEM, DER, and CER. If specified, the SQL Server certificate is checked by verifying if the ServerCertificate provided is an exact match. (Only available in v5.1+) + + + + Initial Catalog or Database - - N/A - + + N/A + The name of the database. The database name can be 128 characters or fewer. - - - - + + + + Integrated Security or Trusted_Connection - - false - + + false + When false, User ID and Password are specified in the connection. When true, the current Windows account credentials are used for authentication. @@ -1587,14 +1587,14 @@ is a more secure way to specify credentials for a connection that uses SQL Server Authentication (Integrated Security=false). - - - - + + + + IP Address Preference or IPAddressPreference - - IPv4First - + + IPv4First + The IP address family preference when establishing TCP connections. If Transparent Network IP Resolution (in .NET Framework) or Multi Subnet Failover is set to true, this setting has no effect. Supported values include: @@ -1603,38 +1603,38 @@ IPAddressPreference=IPv6First IPAddressPreference=UsePlatformDefault - - - - + + + + Load Balance Timeout or Connection Lifetime - - 0 - + + 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. - - - - Max Pool Size - 100 - + + + + 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 - + + + + Min Pool Size + 0 + The minimum number of connections that are allowed in the pool. @@ -1644,14 +1644,14 @@ Values that are greater than Max Pool Size generate an error. - - - - + + + + Multiple Active Result Sets or MultipleActiveResultSets - false - + 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. @@ -1661,14 +1661,14 @@ For more information, see Multiple Active Result Sets (MARS). - - - - + + + + Multi Subnet Failover or MultiSubnetFailover - - false - + + 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: @@ -1678,14 +1678,14 @@ The default is False. For more information about SqlClient's support for Always On AGs, see SqlClient Support for High Availability, Disaster Recovery. - - - - + + + + Network Library or Network or Net - - N/A - + + N/A + The network library used to establish a connection to an instance of SQL Server. Supported values include: @@ -1705,40 +1705,40 @@ Network Library=dbmssocn;Data Source=000.000.000.000,1433; - - - - Packet Size - 8000 - + + + + 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 - + + 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 fewer. - - - - + + + + Persist Security Info or PersistSecurityInfo - - false - + + false + When set to false or no (strongly recommended), security-sensitive information, such as the password or access token, is not returned as part of the connection if the connection is open or has ever been in an open state. This property should only be set to true if your application has a specific need to read the password out of an already-opened database connection. The default value of false is the more secure setting; using true for this property opens your application to security risks such as accidentally logging or tracing the database password. @@ -1748,21 +1748,21 @@ Recognized values are true, false, yes, and no. - - - - + + + + Pool Blocking Period or PoolBlockingPeriod - - Auto - - Sets the blocking period behavior for a connection pool. See property for details. - - - - Pooling - true - + + 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. @@ -1772,28 +1772,28 @@ The value of this key can be true, false, yes, and no. - - - - Replication + + + + Replication false - true if replication is supported using the connection. - - - + true if replication is supported using the connection. + + + Server SPN or ServerSPN - - N/A - + + N/A + The SPN for the data source. The default value is an empty string, which causes SqlClient to use the default, driver-generated SPN. (Only available in v5.0+) - - - - Transaction Binding - Implicit Unbind - + + + + Transaction Binding + Implicit Unbind + Controls connection association with an enlisted System.Transactions transaction. @@ -1813,14 +1813,14 @@ 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.0, 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. - - - - + + + + Transparent Network IP Resolution or TransparentNetworkIPResolution - - See description. - + + 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. @@ -1842,8 +1842,8 @@ The default values are as follows: - - + + false when: @@ -1857,24 +1857,24 @@ Authentication is 'Active Directory Password' or 'Active Directory Integrated' - - true in all other cases. - - - - - + + true in all other cases. + + + + + Trust Server Certificate or TrustServerCertificate - + false - - When set to true, TLS 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. - - - - Type System Version - N/A - + + When set to true, TLS 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. + + + + 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. @@ -1893,42 +1893,42 @@ 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 - + + 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 fewer. - - - - 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. - - - - + + + + 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 local computer name + The name of the workstation connecting to SQL Server. The ID must be 128 characters or fewer. - - - - - The following list contains the valid names for connection pooling values within the . For more information, see SQL Server Connection Pooling (ADO.NET). + + + + + The following list contains the valid names for connection pooling values within the . For more information, see SQL Server Connection Pooling (ADO.NET). Connection Lifetime (or Load Balance Timeout) @@ -1939,16 +1939,16 @@ When you are setting keyword or connection pooling values that require a Boolean value, you can use yed instead of true, and no instead of false. Integer values are represented as strings. - - - 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. - - - Universal data link (UDL) files are not supported for the .NET Framework Data Provider for SQL Server. - - - 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). 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). If you need to construct connection strings based on user input, use the new , which validates the connection string and helps to eliminate this problem. See Connection String Builders for more information. - + + + 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. + + + Universal data link (UDL) files are not supported for the .NET Framework Data Provider for SQL Server. + + + 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). 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). If you need to construct connection strings based on user input, use the new , which validates the connection string and helps to eliminate this problem. See Connection String Builders for more information. +
@@ -1994,18 +1994,18 @@ } - - An invalid connection string argument has been supplied, or a required connection string argument has not been supplied. - -
- - - Gets the time to wait 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. - - + + An invalid connection string argument has been supplied, or a required connection string argument has not been supplied. + + + + + Gets the time to wait 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. + + You can set the amount of time a connection waits to time out by using the Connect Timeout or Connection Timeout keywords in the connection string. A value of 0 indicates no limit, and should be avoided in a because an attempt to connect waits indefinitely. @@ -2049,17 +2049,17 @@ } - - The value set is less than 0. - - - - - Creates and returns a object associated with the . - - - A object. - + + The value set is less than 0. + + + + + Creates and returns a object associated with the . + + + A object. + @@ -2082,34 +2082,34 @@ } - - - - Returns a new instance of the class that implements the class. - - - A new instance of . - - - - - To be added. - - - To be added. - - - To be added. - - - - - Gets or sets the object for this connection. - - - The object for this connection. - - + + + + Returns a new instance of the class that implements the class. + + + A new instance of . + + + + + To be added. + + + To be added. + + + To be added. + + + + + Gets or sets the object for this connection. + + + The object for this connection. + + Persist Security Info = true is required to get the value of the object with . The default value of is null. An exception will be raised: @@ -2128,15 +2128,15 @@ - - - - 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. - - + + + + 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. + + The 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. @@ -2187,14 +2187,14 @@ }
- - - - 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. - + + + + 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. + The following example creates a and displays some of its read-only properties. @@ -2236,96 +2236,96 @@ } - - - - To be added. - - - To be added. - - - To be added. - - - - - To be added. - - - To be added. - - - To be added. - - - - - A reference to an existing in which to enlist. - - - Enlists in the specified transaction as a distributed transaction. - - + + + + To be added. + + + To be added. + + + To be added. + + + + + To be added. + + + To be added. + + + To be added. + + + + + A reference to an existing in which to enlist. + + + Enlists in the specified transaction as a distributed transaction. + + You can use the method to enlist in a distributed transaction. Because it enlists a connection in a instance, takes advantage of functionality available in the namespace for managing distributed transactions, making it preferable to for this purpose. For more information, see 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 . - - - - - A reference to an existing in which to enlist. - - - Enlists in the specified transaction as a distributed transaction. - - - You can use the method to enlist in a distributed transaction. Because it enlists a connection in a instance, takes advantage of functionality available in the namespace for managing distributed transactions, making it preferable to , which uses a object (from namespace). 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. - - - - - Gets or sets the property. - - - if the property has been set; otherwise . - - - - When you set 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. - - - 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. For more information on errors generated by the SQL Server engine, see Database Engine Errors. - - - - - + + + + + A reference to an existing in which to enlist. + + + Enlists in the specified transaction as a distributed transaction. + + + You can use the method to enlist in a distributed transaction. Because it enlists a connection in a instance, takes advantage of functionality available in the namespace for managing distributed transactions, making it preferable to , which uses a object (from namespace). 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. + + + + + Gets or sets the property. + + + if the property has been set; otherwise . + + + + When you set 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. + + + 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. For more information on errors generated by the SQL Server engine, see Database Engine Errors. + + + + + Returns schema information for the data source of this . For more information about scheme, see SQL Server Schema Collections. - - - A that contains schema information. - - - - - 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. - - - - You may need the schema information of the database, tables or columns. This sample: + + + A that contains schema information. + + + + + 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. + + + + You may need the schema information of the database, tables or columns. This sample: Uses GetSchema to get schema information. @@ -2338,79 +2338,79 @@ Before you run the sample, you need to create the sample database, using the following Transact-SQL: - USE [master] - GO + USE [master] + GO - CREATE DATABASE [MySchool] - GO + CREATE DATABASE [MySchool] + GO - USE [MySchool] - GO + USE [MySchool] + GO - SET ANSI_NULLS ON - GO - SET QUOTED_IDENTIFIER ON - GO + SET ANSI_NULLS ON + GO + SET QUOTED_IDENTIFIER ON + GO - CREATE TABLE [dbo].[Course]( - [CourseID] [nvarchar](10) NOT NULL, - [Year] [smallint] NOT NULL, - [Title] [nvarchar](100) NOT NULL, - [Credits] [int] NOT NULL, - [DepartmentID] [int] NOT NULL, - CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED ( - [CourseID] ASC, - [Year] ASC - ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - ) ON [PRIMARY] - GO + CREATE TABLE [dbo].[Course]( + [CourseID] [nvarchar](10) NOT NULL, + [Year] [smallint] NOT NULL, + [Title] [nvarchar](100) NOT NULL, + [Credits] [int] NOT NULL, + [DepartmentID] [int] NOT NULL, + CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED ( + [CourseID] ASC, + [Year] ASC + ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + ) ON [PRIMARY] + GO - SET ANSI_NULLS ON - GO - SET QUOTED_IDENTIFIER ON - GO + SET ANSI_NULLS ON + GO + SET QUOTED_IDENTIFIER ON + GO - CREATE TABLE [dbo].[Department]( - [DepartmentID] [int] IDENTITY(1,1) NOT NULL, - [Name] [nvarchar](50) NOT NULL, - [Budget] [money] NOT NULL, - [StartDate] [datetime] NOT NULL, - [Administrator] [int] NULL, - CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED ( - [DepartmentID] ASC - ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - ) ON [PRIMARY] - GO + CREATE TABLE [dbo].[Department]( + [DepartmentID] [int] IDENTITY(1,1) NOT NULL, + [Name] [nvarchar](50) NOT NULL, + [Budget] [money] NOT NULL, + [StartDate] [datetime] NOT NULL, + [Administrator] [int] NULL, + CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED ( + [DepartmentID] ASC + ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + ) ON [PRIMARY] + GO - INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) - VALUES (N'C1045', 2012, N'Calculus', 4, 7) - INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) - VALUES (N'C1061', 2012, N'Physics', 4, 1) - INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) - VALUES (N'C2021', 2012, N'Composition', 3, 2) - INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) - VALUES (N'C2042', 2012, N'Literature', 4, 2) - SET IDENTITY_INSERT [dbo].[Department] ON - INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) - VALUES (1, N'Engineering', 350000.0000, CAST(0x0000999C00000000 AS DateTime), 2) - INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) - VALUES (2, N'English', 120000.0000, CAST(0x0000999C00000000 AS DateTime), 6) - INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) - VALUES (4, N'Economics', 200000.0000, CAST(0x0000999C00000000 AS DateTime), 4) - INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) - VALUES (7, N'Mathematics', 250024.0000, CAST(0x0000999C00000000 AS DateTime), 3) - SET IDENTITY_INSERT [dbo].[Department] OFF + INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) + VALUES (N'C1045', 2012, N'Calculus', 4, 7) + INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) + VALUES (N'C1061', 2012, N'Physics', 4, 1) + INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) + VALUES (N'C2021', 2012, N'Composition', 3, 2) + INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) + VALUES (N'C2042', 2012, N'Literature', 4, 2) + SET IDENTITY_INSERT [dbo].[Department] ON + INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) + VALUES (1, N'Engineering', 350000.0000, CAST(0x0000999C00000000 AS DateTime), 2) + INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) + VALUES (2, N'English', 120000.0000, CAST(0x0000999C00000000 AS DateTime), 6) + INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) + VALUES (4, N'Economics', 200000.0000, CAST(0x0000999C00000000 AS DateTime), 4) + INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) + VALUES (7, N'Mathematics', 250024.0000, CAST(0x0000999C00000000 AS DateTime), 3) + SET IDENTITY_INSERT [dbo].[Department] OFF - ALTER TABLE [dbo].[Course] - WITH CHECK ADD - CONSTRAINT [FK_Course_Department] FOREIGN KEY([DepartmentID]) - REFERENCES [dbo].[Department] ([DepartmentID]) - GO + ALTER TABLE [dbo].[Course] + WITH CHECK ADD + CONSTRAINT [FK_Course_Department] FOREIGN KEY([DepartmentID]) + REFERENCES [dbo].[Department] ([DepartmentID]) + GO - ALTER TABLE [dbo].[Course] - CHECK CONSTRAINT [FK_Course_Department] - GO - + ALTER TABLE [dbo].[Course] + CHECK CONSTRAINT [FK_Course_Department] + GO + How to Get Schema Information from Database has C# and Visual Basic versions of this code sample in a Visual Studio project. @@ -2594,81 +2594,81 @@ } - - is specified as null. - - - - - 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. - - - - The parameter can supply n depth of values, which are specified by the restrictions collection for a specific collection. In order to set values on a given restriction, and not set the values of other restrictions, you need to set the preceding restrictions to and then put the appropriate value in for the restriction that you would like to specify a value for. - - - An example of this is the "Tables" collection. If the "Tables" collection has three restrictions--database, owner, and table name--and you want to get back only the tables associated with the owner "Carl", you need to pass in the following values: null, "Carl". If a restriction value is not passed in, the default values are used for that restriction. This is the same mapping as passing in , which is different from passing in an empty string for the parameter value. In that case, the empty string ("") is considered to be the value for the specified parameter. - + + is specified as null. + + + + + 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. + + + + The parameter can supply n depth of values, which are specified by the restrictions collection for a specific collection. In order to set values on a given restriction, and not set the values of other restrictions, you need to set the preceding restrictions to and then put the appropriate value in for the restriction that you would like to specify a value for. + + + An example of this is the "Tables" collection. If the "Tables" collection has three restrictions--database, owner, and table name--and you want to get back only the tables associated with the owner "Carl", you need to pass in the following values: null, "Carl". If a restriction value is not passed in, the default values are used for that restriction. This is the same mapping as passing in , which is different from passing in an empty string for the parameter value. In that case, the empty string ("") is considered to be the value for the specified parameter. + For a code sample demonstrating , see . - - is specified as null. - - - - - - Occurs when SQL Server returns a warning or informational message. - - - - Clients that want to process warnings or informational messages sent by the server should create an 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. - For more information and an example, see Connection Events. - - - - - - To be added. - - - To be added. - - - To be added. - - - - - Opens a database connection with the property settings specified by the . - - - - 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. - - - If the goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling . - - - 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. - - - 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. - + + is specified as null. + + + + + + Occurs when SQL Server returns a warning or informational message. + + + + Clients that want to process warnings or informational messages sent by the server should create an 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. + For more information and an example, see Connection Events. + + + + + + To be added. + + + To be added. + + + To be added. + + + + + Opens a database connection with the property settings specified by the . + + + + 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. + + + If the goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling . + + + 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. + + + 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. + @@ -2711,44 +2711,44 @@ } - + Cannot open a connection without specifying a data source or server. 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 <system.data.localdb> tag in the app.config file has invalid or unknown elements. - - - There are two entries with the same name in the <localdbinstances> section. - - - - - Options to override default connection open behavior. - - - Opens a database connection with the property settings specified by the . - - - - 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. If overrides are specified, the first open attempt will apply the specified overrides to the open action. - - - If the goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling . - - - 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. - - - 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. - + + + There are two entries with the same name in the <localdbinstances> section. + + + + + Options to override default connection open behavior. + + + Opens a database connection with the property settings specified by the . + + + + 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. If overrides are specified, the first open attempt will apply the specified overrides to the open action. + + + If the goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling . + + + 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. + + + 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. + @@ -2791,63 +2791,63 @@ } - + Cannot open a connection without specifying a data source or server. 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 <system.data.localdb> tag in the app.config file has invalid or unknown elements. - - - There are two entries with the same name in the <localdbinstances> section. - - - - - 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. - - - - After calling , 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. - - - + + + 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 <system.data.localdb> tag in the app.config file has invalid or unknown elements. + + + There are two entries with the same name in the <localdbinstances> section. + + + + + 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. + + + + After calling , 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. + + + Calling more than once for the same instance before task completion. 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. - - - - - 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. - - - - If an application performs bulk copy operations, or sends or receives lots of text or image data, a packet size larger than the default may improve efficiency because it causes fewer network read and write operations. If an application sends and receives small amounts of information, you can set the packet size to 512 bytes (using the Packet Size value in the ), 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. - + + + Any error returned by SQL Server that occurred while opening the connection. + + + + + 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. + + + + If an application performs bulk copy operations, or sends or receives lots of text or image data, a packet size larger than the default may improve efficiency because it causes fewer network read and write operations. If an application sends and receives small amounts of information, you can set the packet size to 512 bytes (using the Packet Size value in the ), 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. + @@ -2889,19 +2889,19 @@ } - - - - Dictionary of custom column encryption key store providers - - + + + + Dictionary of custom column encryption key store providers + + Registers the column encryption key store providers. This function should only be called once in an app. This does shallow copying of the dictionary so that the app cannot alter the custom provider list once it has been set. The built-in column master key store providers that are available for the Windows Certificate Store, CNG Store and CSP are pre-registered. - + Dictionary<string, SqlColumnEncryptionKeyStoreProvider> customKeyStoreProviders = new Dictionary<string, SqlColumnEncryptionKeyStoreProvider>(); @@ -2910,27 +2910,27 @@ SqlConnection.RegisterColumnEncryptionKeyStoreProviders(customKeyStoreProviders); - + A null dictionary was provided. A string key in the dictionary was null or empty. A value in the dictionary was null. - - - A string key in the dictionary started with "MSSQL_". This prefix is reserved for system providers. - - - This function was called more than once. - - - - - Dictionary of custom column encryption key providers - - - Registers the encryption key store providers on the instance. If this function has been called, any providers registered using the static methods will be ignored. This function can be called more than once. This does shallow copying of the dictionary so that the app cannot alter the custom provider list once it has been set. - + + + A string key in the dictionary started with "MSSQL_". This prefix is reserved for system providers. + + + This function was called more than once. + + + + + Dictionary of custom column encryption key providers + + + Registers the encryption key store providers on the instance. If this function has been called, any providers registered using the static methods will be ignored. This function can be called more than once. This does shallow copying of the dictionary so that the app cannot alter the custom provider list once it has been set. + Custom master key store providers can be registered with the driver at three different layers. The precedence of the three registrations is as follows: @@ -2964,49 +2964,49 @@ - A string key in the dictionary started with "MSSQL_". This prefix is reserved for system providers. + A string key in the dictionary started with "MSSQL_". This prefix is reserved for system providers. - - - - Gets or sets a value that specifies the object bound to this command. - - - When set to null (default), the default non-retryable provider will be applied. - - - - You must set the value for this property before opening the connection to take effect. - - - To apply the retry logic, do the following steps before opening the connection: - - - + + + + Gets or sets a value that specifies the object bound to this command. + + + When set to null (default), the default non-retryable provider will be applied. + + + + You must set the value for this property before opening the connection to take effect. + + + To apply the retry logic, do the following steps before opening the connection: + + + Define the configuration parameters by using type. - - Create a by using one of the following static methods of the class: - - - - - - - - + + Create a by using one of the following static methods of the class: + + + + + + + + Assign the object to the RetryLogicProvider property. - - - Detecting retryable exceptions is a vital part of the retry pattern. Before applying retry logic, it is important to investigate exceptions and choose a retry provider that best fits your scenario. First, log your exceptions and find transient faults. - - - The connection timeout restarts for each execution of a connection open. There is no timing overlap between these two actions. - - - The default retry logic provider is not enabled unless it is configured in an application configuration file. For more information, see Configurable retry logic and configuration file. - + + + Detecting retryable exceptions is a vital part of the retry pattern. Before applying retry logic, it is important to investigate exceptions and choose a retry provider that best fits your scenario. First, log your exceptions and find transient faults. + + + The connection timeout restarts for each execution of a connection open. There is no timing overlap between these two actions. + + + The default retry logic provider is not enabled unless it is configured in an application configuration file. For more information, see Configurable retry logic and configuration file. + @@ -3119,67 +3119,67 @@ } - - - - If statistics gathering is enabled, all values are reset to zero. - - - If statistics gathering is not enabled and this method is called, no error is thrown. - - - - - Returns a name value pair collection of statistics at the point in time the method is called. - - - Returns a reference of type of items. - - - When this method is called, the values retrieved are those at the current point in time. If you continue using the connection, the values are incorrect. You need to re-execute the method to obtain the most current values. - - - - - Returns a name value pair collection of internal properties at the point in time the method is called. - - - Returns a reference of type of (string, object) items. - - - - When this method is called, the values retrieved are those at the current point in time. If you continue using the connection, the values are incorrect. You need to re-execute the method to obtain the most current values. - - - - Supported internal properties - Type - Information provided - Return value - - - SQLDNSCachingSupportedState - string - To indicate the IsSupported flag sent by the server for DNS Caching - "true", "false", "innerConnection is null!" - - - SQLDNSCachingSupportedStateBeforeRedirect - string - To indicate the IsSupported flag sent by the server for DNS Caching before redirection. - "true", "false", "innerConnection is null!" - - - - - - - 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. - - + + + + If statistics gathering is enabled, all values are reset to zero. + + + If statistics gathering is not enabled and this method is called, no error is thrown. + + + + + Returns a name value pair collection of statistics at the point in time the method is called. + + + Returns a reference of type of items. + + + When this method is called, the values retrieved are those at the current point in time. If you continue using the connection, the values are incorrect. You need to re-execute the method to obtain the most current values. + + + + + Returns a name value pair collection of internal properties at the point in time the method is called. + + + Returns a reference of type of (string, object) items. + + + + When this method is called, the values retrieved are those at the current point in time. If you continue using the connection, the values are incorrect. You need to re-execute the method to obtain the most current values. + + + + Supported internal properties + Type + Information provided + Return value + + + SQLDNSCachingSupportedState + string + To indicate the IsSupported flag sent by the server for DNS Caching + "true", "false", "innerConnection is null!" + + + SQLDNSCachingSupportedStateBeforeRedirect + string + To indicate the IsSupported flag sent by the server for DNS Caching before redirection. + "true", "false", "innerConnection is null!" + + + + + + + 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. + + The version is of the form ##.##.####, where the first two digits are the major version, the next two digits are the minor version, and the last four digits are the release version. The string is of the form major.minor.build, where major and minor are exactly two digits and build is exactly four digits. was called while the returned Task was not completed and the connection was not opened after a call to . @@ -3217,67 +3217,67 @@ } - - The connection is closed. was called while the returned Task was not completed and the connection was not opened after a call to . - - - - - Gets the server process ID (SPID) of the active connection. - - - The server process ID (SPID) of the active connection. - - - Returns 0 if the connection is inactive on the client side. - - - - - Indicates the state of the during the most recent network operation performed on the connection. - - - An enumeration. - - - Returns an enumeration indicating the state of the . Closing and reopening the connection will refresh the value of . - - - - - When set to , enables statistics gathering for the current connection. - - - Returns if statistics gathering is enabled; otherwise . is the default. - - - Enabling statistics gathering has a minor, but measurable effect on performance and therefore should be enabled only when it is required. - - - - - Creates a new object that is a copy of the current instance. - - - A new object that is a copy of this instance. - - - - This member is an explicit interface member implementation. It can be used only when the instance is cast to an interface. - - - This member is only supported by the .NET Compact Framework. - - - - - - 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. - - + + The connection is closed. was called while the returned Task was not completed and the connection was not opened after a call to . + + + + + Gets the server process ID (SPID) of the active connection. + + + The server process ID (SPID) of the active connection. + + + Returns 0 if the connection is inactive on the client side. + + + + + Indicates the state of the during the most recent network operation performed on the connection. + + + An enumeration. + + + Returns an enumeration indicating the state of the . Closing and reopening the connection will refresh the value of . + + + + + When set to , enables statistics gathering for the current connection. + + + Returns if statistics gathering is enabled; otherwise . is the default. + + + Enabling statistics gathering has a minor, but measurable effect on performance and therefore should be enabled only when it is required. + + + + + Creates a new object that is a copy of the current instance. + + + A new object that is a copy of this instance. + + + + This member is an explicit interface member implementation. It can be used only when the instance is cast to an interface. + + + This member is only supported by the .NET Compact Framework. + + + + + + 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. + + The string typically contains the network name of the client. The property corresponds to the Workstation ID connection string property. @@ -3321,6 +3321,6 @@ } - - + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionAttestationProtocol.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionAttestationProtocol.xml index 3b93c3e844..a2cbd38e2f 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionAttestationProtocol.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionAttestationProtocol.xml @@ -1,41 +1,41 @@  - - - - Specifies a value for Attestation Protocol. - - - - - If the attestation protocol is not specified. Use this as default value. - - - 0 - - - - - Attestation protocol for Azure Attestation Service - - - 1 - - - - - Attestation protocol for no attestation. Only compatible with Virtualization-based security (VBS) enclaves. An Enclave Attestation Url is not required when using this protocol. - - - 2 - - - - - Attestation protocol for Host Guardian Service - - - 3 - - - + + + + Specifies a value for Attestation Protocol. + + + + + If the attestation protocol is not specified. Use this as default value. + + + 0 + + + + + Attestation protocol for Azure Attestation Service + + + 1 + + + + + Attestation protocol for no attestation. Only compatible with Virtualization-based security (VBS) enclaves. An Enclave Attestation Url is not required when using this protocol. + + + 2 + + + + + Attestation protocol for Host Guardian Service + + + 3 + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionColumnEncryptionSetting.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionColumnEncryptionSetting.xml index ea99bf42b8..68dc82a65a 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionColumnEncryptionSetting.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionColumnEncryptionSetting.xml @@ -1,19 +1,19 @@  - - - - Note that these settings cannot be used to bypass encryption and gain access to plaintext data. For details, see Always Encrypted (Database Engine). - - - - - Specifies the connection does not use Always Encrypted. Should be used if no queries sent over the connection access encrypted columns. - - - - - Enables Always Encrypted functionality for the connection. Query parameters that correspond to encrypted columns will be transparently encrypted and query results from encrypted columns will be transparently decrypted. - - - - \ No newline at end of file + + + + Note that these settings cannot be used to bypass encryption and gain access to plaintext data. For details, see Always Encrypted (Database Engine). + + + + + Specifies the connection does not use Always Encrypted. Should be used if no queries sent over the connection access encrypted columns. + + + + + Enables Always Encrypted functionality for the connection. Query parameters that correspond to encrypted columns will be transparently encrypted and query results from encrypted columns will be transparently decrypted. + + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptOption.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptOption.xml index 7a0dc7b54e..a582da8168 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptOption.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptOption.xml @@ -1,89 +1,89 @@  - - - - These options are used to control encryption behavior of the communication between the server and the client. - - - Implicit conversions have been added to maintain backwards compatibility with boolean behavior for the property. When converting from a boolean, a value of converts to and a value of converts to . When converting to a boolean, , , and convert to and converts . - - - - - Converts the specified string representation of a logical value to its equivalent. - - - A string containing the value to convert. - - - An object that is equivalent to contained in . - - - Throws exception if provided is not convertible to type. - - - - - Converts the specified string representation of a logical value to its equivalent and returns a value that indicates whether the conversion succeeded. - - - A string containing the value to convert. - - - An object that is equivalent to contained in . if conversion fails. - - - if the parameter was converted successfully; otherwise, . - - - This method does not throw an exception if conversion fails. - - - - - Specifies that TLS encryption is optional when connecting to the server. If the server requires encryption, encryption will be negotiated. - - - - - Specifies that TLS encryption is required when connecting to the server. If the server doesn't support encryption, the connection will fail. - - - - - Enables and requires TDS 8.0, TLS encryption to the server. If the server doesn't support TDS 8.0, TLS encryption, the connection will fail. - - - - - The boolean value to be used for implicit comparison. - - - Enables implicit conversion of a boolean to a . A value of converts to . A value of converts to . - - - - - The value to be used for implicit comparison. - - - Enables implicit conversion of a to a boolean. and convert to . converts to . - - - - - Returns the string value of . - - - - - Compares the representation of to another . - - - - - Returns the hash code of the value. - - - + + + + These options are used to control encryption behavior of the communication between the server and the client. + + + Implicit conversions have been added to maintain backwards compatibility with boolean behavior for the property. When converting from a boolean, a value of converts to and a value of converts to . When converting to a boolean, , , and convert to and converts . + + + + + Converts the specified string representation of a logical value to its equivalent. + + + A string containing the value to convert. + + + An object that is equivalent to contained in . + + + Throws exception if provided is not convertible to type. + + + + + Converts the specified string representation of a logical value to its equivalent and returns a value that indicates whether the conversion succeeded. + + + A string containing the value to convert. + + + An object that is equivalent to contained in . if conversion fails. + + + if the parameter was converted successfully; otherwise, . + + + This method does not throw an exception if conversion fails. + + + + + Specifies that TLS encryption is optional when connecting to the server. If the server requires encryption, encryption will be negotiated. + + + + + Specifies that TLS encryption is required when connecting to the server. If the server doesn't support encryption, the connection will fail. + + + + + Enables and requires TDS 8.0, TLS encryption to the server. If the server doesn't support TDS 8.0, TLS encryption, the connection will fail. + + + + + The boolean value to be used for implicit comparison. + + + Enables implicit conversion of a boolean to a . A value of converts to . A value of converts to . + + + + + The value to be used for implicit comparison. + + + Enables implicit conversion of a to a boolean. and convert to . converts to . + + + + + Returns the string value of . + + + + + Compares the representation of to another . + + + + + Returns the hash code of the value. + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionIPAddressPreference.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionIPAddressPreference.xml index c07d30ecce..d806583ebc 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionIPAddressPreference.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionIPAddressPreference.xml @@ -1,38 +1,38 @@  - - - - Specifies a value for IP address preference during a TCP connection. - - - If Multi Subnet Failover or Transparent Network IP Resolution is set to true, this setting has no effect. - - - - - Specifies a value for IP address preference during a TCP connection. - - - If Multi Subnet Failover is set to true, this setting has no effect. - - - - - Connects using IPv4 address(es) first. If the connection fails, try IPv6 address(es), if provided. This is the default value. - - 0 - - - - Connect using IPv6 address(es) first. If the connection fails, try IPv4 address(es), if available. - - 1 - - - - Connects with IP addresses in the order the underlying platform or operating system provides them. - - 2 - - + + + + Specifies a value for IP address preference during a TCP connection. + + + If Multi Subnet Failover or Transparent Network IP Resolution is set to true, this setting has no effect. + + + + + Specifies a value for IP address preference during a TCP connection. + + + If Multi Subnet Failover is set to true, this setting has no effect. + + + + + Connects using IPv4 address(es) first. If the connection fails, try IPv6 address(es), if provided. This is the default value. + + 0 + + + + Connect using IPv6 address(es) first. If the connection fails, try IPv4 address(es), if available. + + 1 + + + + Connects with IP addresses in the order the underlying platform or operating system provides them. + + 2 + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionOverrides.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionOverrides.xml index 06549e7e68..8c563e08d3 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionOverrides.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionOverrides.xml @@ -1,25 +1,25 @@  - - - - Specifies a value for Overrides. - - - - - No overrides. - - - 0 - - - - - Disable transient fault handling during the initial attempt. - - - 1 - - - + + + + Specifies a value for Overrides. + + + + + No overrides. + + + 0 + + + + + Disable transient fault handling during the initial attempt. + + + 1 + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlCredential.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlCredential.xml index 686c0fb6e1..c7a630eb1f 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlCredential.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlCredential.xml @@ -1,12 +1,12 @@  - - - + + + provides a more secure way to specify the password for a login attempt using SQL Server Authentication. is comprised of a user id and a password that will be used for SQL Server Authentication. The password in a object is of type . cannot be inherited. Windows Authentication (Integrated Security = true) remains the most secure way to log in to a SQL Server database. - - - Use to get or set a connection's object. Use to change the password for a object. For information on how a object affects connection pool behavior, see SQL Server Connection Pooling (ADO.NET). + + + Use to get or set a connection's object. Use to change the password for a object. For information on how a object affects connection pool behavior, see SQL Server Connection Pooling (ADO.NET). An exception will be raised if a non-null object is used in a connection with any of the following connection string keywords: @@ -48,45 +48,45 @@ } - - - - The user id. - - - The password; a value marked as read-only. Passing a read/write parameter will raise an . - - - Creates an object of type . - - + + + + The user id. + + + The password; a value marked as read-only. Passing a read/write parameter will raise an . + + + Creates an object of type . + + The constructor does not accept null parameters. An string.Empty value is allowed. An attempt to pass a null parameter in the constructor will raise an exception. - - - Overview of the SqlClient driver - - - - - Gets the password component of the object. - - - The password component of the object. - - - Overview of the SqlClient driver - - - - - Gets the user ID component of the object. - - - The user ID component of the object. - - - Overview of the SqlClient driver - - - + + + Overview of the SqlClient driver + + + + + Gets the password component of the object. + + + The password component of the object. + + + Overview of the SqlClient driver + + + + + Gets the user ID component of the object. + + + The user ID component of the object. + + + Overview of the SqlClient driver + + + From ca25b5dd8c147be378016ffc8b5663b035156992 Mon Sep 17 00:00:00 2001 From: Ben Russell Date: Wed, 18 Sep 2024 17:41:08 -0500 Subject: [PATCH 4/4] Using new sample file --- .../SqlConnection.xml | 57 ++++++++++++------- 1 file changed, 38 insertions(+), 19 deletions(-) diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml index 2bacd40540..f7ca3d1237 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml @@ -280,10 +280,13 @@ using System; - using System.Data; + using System.Collections.Concurrent; + using System.Threading; + using System.Threading.Tasks; + using Azure.Core; using Azure.Identity; using Microsoft.Data.SqlClient; - + class Program { static void Main() @@ -291,26 +294,42 @@ OpenSqlConnection(); Console.ReadLine(); } - + + const string defaultScopeSuffix = "/.default"; + + // Reuse credential objects to take advantage of underlying token caches + private static ConcurrentDictionar<string, DefaultAzureCredential> credentials = new ConcurrentDictionary<string, DefaultAzureCredential>(); + + // Use a shared callback function for connections that should be in the same connection pool + private static Func<SqlAuthenticationParameters, CancellationToken, Task<SqlAuthenticationToken>> myAccessTokenCallback = + async (authParams, cancellationToken) => + { + string scope = authParams.Resource.EndsWith(defaultScopeSuffix) + ? authParams.Resource + : $"{authParams.Resource}{defaultScopeSuffix}"; + + DefaultAzureCredentialOptions options = new DefaultAzureCredentialOptions(); + options.ManagedIdentityClientId = authParams.UserId; + + // Reuse the same credential object if we are using the same MI Client ID + AccessToken token = await credentials.GetOrAdd(authParams.UserId, new DefaultAzureCredential(options)).GetTokenAsync( + new TokenRequestContext(new string[] { scope }), + cancellationToken); + + return new SqlAuthenticationToken(token.Token, token.ExpiresOn); + }; + private static void OpenSqlConnection() { - const string defaultScopeSuffix = "/.default"; - string connectionString = GetConnectionString(); - DefaultAzureCredential credential = new(); - - using (SqlConnection connection = new(connectionString) + // (Optional) Pass a User-Assigned Managed Identity Client ID. + // This will ensure different MI Client IDs are in different connection pools. + string connectionString = "Server=myServer.database.windows.net;Encrypt=Mandatory;UserId=<ManagedIdentityClientId>;"; + + using (SqlConnection connection = new SqlConnection(connectionString) { - AccessTokenCallback = async (authParams, cancellationToken) => - { - string scope = authParams.Resource.EndsWith(defaultScopeSuffix) - ? authParams.Resource - : $"{authParams.Resource}{defaultScopeSuffix}"; - AccessToken token = await credential.GetTokenAsync( - new TokenRequestContext([scope]), - cancellationToken); - - return new SqlAuthenticationToken(token.Token, token.ExpiresOn); - } + // The callback function is part of the connection pool key. Using a static callback function + // ensures connections will not create a new pool per connection just for the callback. + AccessTokenCallback = myAccessTokenCallback }) { connection.Open();