diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlBatchCommandCollection.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlBatchCommandCollection.xml index d45c4535cf..aa3b2de178 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlBatchCommandCollection.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlBatchCommandCollection.xml @@ -1,4 +1,4 @@ - + @@ -95,7 +95,7 @@ - The object to remove from the . + The object to remove from the . Removes the specified object from the collection. diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlClientDiagnostic.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlClientDiagnostic.xml index 5ac5e9028a..69d25c9b14 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlClientDiagnostic.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlClientDiagnostic.xml @@ -1,4 +1,4 @@ - + Class that provides strongly-typed collection of key-value pairs for SqlClient diagnostic objects. diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlClientLogger.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlClientLogger.xml index c093bbd505..02748edca4 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlClientLogger.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlClientLogger.xml @@ -1,47 +1,84 @@ - - - Represents a SQL client logger. - To be added. - - - Initializes a new instance of the class. - To be added. - - - Gets a value that indicates whether bid tracing is enabled. - - if bid tracing is enabled; otherwise, . - To be added. - - - to log the message; otherwise, . - The type to be logged. - The logging method. - The message to be logged. - Logs the specified message if is . - if the message is not logged; otherwise, . - To be added. - - - The type to be logged. - The logging method. - The message to be logged. - Logs an error through a specified method of the current instance type. - To be added. - - - The type to be logged. - The logging method. - The message to be logged. - Logs information through a specified method of the current instance type. - To be added. - - - The type to be logged. - The logging method. - The message to be logged. - Logs warning through a specified method of the current instance type. - - + + + + Represents a SQL client logger. + + + + + Initializes a new instance of the class. + + + + + Gets a value that indicates whether bid tracing is enabled. + + + if bid tracing is enabled; otherwise, . + + + + + to log the message; otherwise, . + + + The type to be logged. + + + The logging method. + + + The message to be logged. + + + Logs the specified message if is . + + + if the message is not logged; otherwise, . + + + + + The type to be logged. + + + The logging method. + + + The message to be logged. + + + Logs an error through a specified method of the current instance type. + + + + + The type to be logged. + + + The logging method. + + + The message to be logged. + + + Logs information through a specified method of the current instance type. + + + + + The type to be logged. + + + The logging method. + + + The message to be logged. + + + Logs warning through a specified method of the current instance type. + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlClientMetaDataCollectionNames.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlClientMetaDataCollectionNames.xml index 01d30ee8d3..74bf4f9195 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlClientMetaDataCollectionNames.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlClientMetaDataCollectionNames.xml @@ -1,68 +1,84 @@ - - - Provides a list of constants for use with the **GetSchema** method to retrieve metadata collections. - To be added. - - - A constant for use with the **GetSchema** method that represents the **Columns** collection. - To be added. - - - A constant for use with the **GetSchema** method that represents the **Databases** collection. - To be added. - - - A constant for use with the **GetSchema** method that represents the **ForeignKeys** collection. - To be added. - - - A constant for use with the **GetSchema** method that represents the **IndexColumns** collection. - To be added. - - - A constant for use with the **GetSchema** method that represents the **Indexes** collection. - To be added. - - - A constant for use with the **GetSchema** method that represents the **ProcedureParameters** collection. - To be added. - - - A constant for use with the **GetSchema** method that represents the **Procedures** collection. - To be added. - - - A constant for use with the **GetSchema** method that represents the **Tables** collection. - To be added. - - - A constant for use with the **GetSchema** method that represents the **UserDefinedTypes** collection. - To be added. - - - A constant for use with the **GetSchema** method that represents the **Users** collection. - To be added. - - - A constant for use with the **GetSchema** method that represents the **ViewColumns** collection. - To be added. - - - A constant for use with the **GetSchema** method that represents the **Views** collection. - To be added. - - - A constant for use with the **GetSchema** method that represents the **AllColumns** collection. - To be added. - - - A constant for use with the **GetSchema** method that represents the **ColumnSetColumns** collection. - To be added. - - - A constant for use with the **GetSchema** method that represents the **StructuredTypeMembers** collection. - To be added. - - + + + + Provides a list of constants for use with the method to retrieve metadata collections. + + + + + A constant for use with the method that represents the Columns collection. + + + + + A constant for use with the method that represents the Databases collection. + + + + + A constant for use with the method that represents the ForeignKeys collection. + + + + + A constant for use with the method that represents the IndexColumns collection. + + + + + A constant for use with the method that represents the Indexes collection. + + + + + A constant for use with the method that represents the ProcedureParameters collection. + + + + + A constant for use with the method that represents the Procedures collection. + + + + + A constant for use with the method that represents the Tables collection. + + + + + A constant for use with the method that represents the UserDefinedTypes collection. + + + + + A constant for use with the method that represents the Users collection. + + + + + A constant for use with the method that represents the ViewColumns collection. + + + + + A constant for use with the method that represents the Views collection. + + + + + A constant for use with the method that represents the AllColumns collection. + + + + + A constant for use with the method that represents the ColumnSetColumns collection. + + + + + A constant for use with the method that represents the StructuredTypeMembers collection. + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlClientPermission.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlClientPermission.xml index c9b4ff0c38..0c7ba2ff03 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlClientPermission.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlClientPermission.xml @@ -1,153 +1,166 @@ - - - Enables the .NET Framework Data Provider for SQL Server to help make sure that a user has a security level sufficient to access a data source. - - property takes precedence over the property. -Therefore, if you set to `false`, you must also set -to `false` to prevent a user from making a connection using a blank password. - -> [!NOTE] -> When using code access security permissions for ADO.NET, the correct pattern is to start with the most restrictive case (no permissions at all) and then add the specific permissions that -are needed for the particular task that the code needs to perform. The opposite pattern, starting with all permissions and then denying a specific permission, -is not secure, because there are many ways of expressing the same connection string. For example, if you start with all permissions and then attempt to deny the use of the connection -string "server=someserver", the string "server=someserver.mycompany.com" would still be allowed. By always starting by granting no permissions at all, you reduce the chances that there are -holes in the permission set. - -]]> - - - - Initializes a new instance of the class. - To be added. - - - One of the values. - Initializes a new instance of the class. - To be added. - - - One of the values. - Indicates whether a blank password is allowed. - Initializes a new instance of the class. - - enumeration takes precedence over the property. -Therefore, if you set to `false`, you must also set to `None` to -prevent a user from making a connection using a blank password. For an example demonstrating how to use security demands, see [Code Access Security and -ADO.NET](/dotnet/framework/data/adonet/code-access-security). - -]]> - - - - The connection string. - The key restrictions. - One of the enumerations. - Adds a new connection string and a set of restricted keywords to the object. - - [!NOTE] -> When using code access security permissions for ADO.NET, the correct pattern is to start with the most restrictive case (no permissions at all) and then add the specific permissions that are -needed for the particular task that the code needs to perform. The opposite pattern, starting with all permissions and then trying to deny a specific permission, is not secure, because there are -many ways of expressing the same connection string. For example, if you start with all permissions and then attempt to deny the use of the connection string "server=someserver", -the string "server=someserver.mycompany.com" would still be allowed. By always starting by granting no permissions at all, you reduce the chances that there are holes in the permission set. - - ]]> - - - - Returns the as an . - A copy of the current permission object. - To be added. - - - Creates an XML encoding of the security object and its current state. - An XML encoding of the security object, including any state information. - - and methods to make the objects security encodable. - -]]> - - - - The XML encoding to use to reconstruct the security object. - Reconstructs a security object with a specified state from an XML encoding. - - - - - - A permission object to combine with the current permission object. It must be of the same type as the current permission object. - Returns a new permission object that is the union of the current and specified permission objects. - A new permission object that represents the union of the current permission object and the specified permission object. - - is a permission that represents all the operations permitted by both the current permission object and the specified permission object. Any demand that passes either permission passes their union. - -]]> - - The object is not the same type as the current permission object. - - - A permission object that is to be tested for the subset relationship. This object must be of the same type as the current permission object. - Returns a value indicating whether the current permission object is a subset of the specified permission object. - - if the current permission object is a subset of the specified permission object, otherwise . - - - - The parameter is an object that is not of the same type as the current permission object. - - - A permission object to intersect with the current permission object. It must be of the same type as the current permission object. - Returns a new permission object representing the intersection of the current permission object and the specified permission object. - A new permission object that represents the intersection of the current permission object and the specified permission object. This new permission object is a null reference ( in Visual Basic) if the intersection is empty. - - - - The parameter is not a null reference ( in Visual Basic) and is not an instance of the same class as the current permission object. - - + + + + Enables the .NET Framework Data Provider for SQL Server to help make sure that a user has a security level sufficient to access a data source. + + + + The property takes precedence over the property. Therefore, if you set to , you must also set to to prevent a user from making a connection using a blank password. + + + When using code access security permissions for ADO.NET, the correct pattern is to start with the most restrictive case (no permissions at all) and then add the specific permissions that are needed for the particular task that the code needs to perform. The opposite pattern, starting with all permissions and then denying a specific permission, is not secure, because there are many ways of expressing the same connection string. For example, if you start with all permissions and then attempt to deny the use of the connection string "server=someserver", the string "server=someserver.mycompany.com" would still be allowed. By always starting by granting no permissions at all, you reduce the chances that there are holes in the permission set. + + + + + + Initializes a new instance of the class. + + + + + One of the values. + + + Initializes a new instance of the class. + + + + + One of the values. + + + Indicates whether a blank password is allowed. + + + Initializes a new instance of the class. + + + The enumeration takes precedence over the property. Therefore, if you set to , you must also set to None to prevent a user from making a connection using a blank password. For an example demonstrating how to use security demands, see Code Access Security and ADO.NET. + + + + + The connection string. + + + The key restrictions. + + + One of the enumerations. + + + Adds a new connection string and a set of restricted keywords to the object. + + + + Use this method to configure which connection strings are allowed by a particular permission object. For example, use the following code fragment if you want to only allow a specific connection string and nothing else: + + + permission.Add("server=MyServer; database=MyDatabase; Integrated Security=true", "", KeyRestrictionBehavior.AllowOnly) + + + When using code access security permissions for ADO.NET, the correct pattern is to start with the most restrictive case (no permissions at all) and then add the specific permissions that are needed for the particular task that the code needs to perform. The opposite pattern, starting with all permissions and then trying to deny a specific permission, is not secure, because there are many ways of expressing the same connection string. For example, if you start with all permissions and then attempt to deny the use of the connection string "server=someserver", the string "server=someserver.mycompany.com" would still be allowed. By always starting by granting no permissions at all, you reduce the chances that there are holes in the permission set. + + + + + The following example allows connection strings that use any database, but only on the server named MyServer, with any user and password combination and containing no other connection string keywords: + + + permission.Add("server=MyServer;", "database=; user id=; password=;", KeyRestrictionBehavior.AllowOnly) + + + + + The following example uses the same scenario as above but allows for a failover partner that can be used when connecting to servers configured for mirroring: + + + permission.Add("server=MyServer; failover partner=MyMirrorServer", "database=; user id=; password=;", KeyRestrictionBehavior.AllowOnly) + + + + + + Returns the as an . + + + A copy of the current permission object. + + + + + Creates an XML encoding of the security object and its current state. + + + An XML encoding of the security object, including any state information. + + + Custom code that extends security objects must implement the and methods to make the objects security encodable. + + + + + The XML encoding to use to reconstruct the security object. + + + Reconstructs a security object with a specified state from an XML encoding. + + + Custom code that extends security objects needs to implement the and methods to make the objects security encodable. + + + + + A permission object to combine with the current permission object. It must be of the same type as the current permission object. + + + Returns a new permission object that is the union of the current and specified permission objects. + + + A new permission object that represents the union of the current permission object and the specified permission object. + + + The result of a call to is a permission that represents all the operations permitted by both the current permission object and the specified permission object. Any demand that passes either permission passes their union. + + + The object is not the same type as the current permission object. + + + + + A permission object that is to be tested for the subset relationship. This object must be of the same type as the current permission object. + + + Returns a value indicating whether the current permission object is a subset of the specified permission object. + + + if the current permission object is a subset of the specified permission object, otherwise . + + + The current permission object is a subset of the specified permission object if the current permission object specifies a set of operations that is wholly contained by the specified permission object. For example, a permission that represents access to C:\example.txt is a subset of a permission that represents access to C:\. If this method returns , the current permission object represents no more access to the protected resource than does the specified permission object. + + + The parameter is an object that is not of the same type as the current permission object. + + + + + A permission object to intersect with the current permission object. It must be of the same type as the current permission object. + + + Returns a new permission object representing the intersection of the current permission object and the specified permission object. + + + A new permission object that represents the intersection of the current permission object and the specified permission object. This new permission object is a null reference ( in Visual Basic) if the intersection is empty. + + + The intersection of two permissions is a permission that describes the set of operations they both describe. Only a demand that passes both original permissions will pass the intersection. + + + The parameter is not a null reference ( in Visual Basic) and is not an instance of the same class as the current permission object. + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlClientPermissionAttribute.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlClientPermissionAttribute.xml index 3c52bb4303..2d90c4867e 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlClientPermissionAttribute.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlClientPermissionAttribute.xml @@ -1,18 +1,25 @@ - - - Associates a security action with a custom security attribute. - To be added. - - - One of the values representing an action that can be performed by using declarative security. - Initializes a new instance of the class. - To be added. - - - Returns a object that is configured according to the attribute properties. - A object. - To be added. - - + + + + Associates a security action with a custom security attribute. + + + + + One of the values representing an action that can be performed by using declarative security. + + + Initializes a new instance of the class. + + + + + Returns a object that is configured according to the attribute properties. + + + A object. + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionCertificateStoreProvider.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionCertificateStoreProvider.xml index 697e9b8539..c7529fc744 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionCertificateStoreProvider.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionCertificateStoreProvider.xml @@ -1,61 +1,84 @@ - - - The implementation of the key store provider for Windows Certificate Store. This class enables using certificates stored in the Windows Certificate Store as column master keys. - For details, see Always Encrypted. - - To be added. - - - Key store provider for Windows Certificate Store. - To be added. - - - The master key path. - The encryption algorithm. Currently, the only valid value is: RSA_OAEP - - The encrypted column encryption key. - Decrypts the specified encrypted value of a column encryption key. The encrypted value is expected to be encrypted using the certificate with the specified key path and using the specified - algorithm. The format of the key path should be "Local Machine/My/<certificate_thumbprint>" or "Current User/My/<certificate_thumbprint>". - - Returns -. The decrypted column encryption key. - To be added. - - - The master key path. - The encryption algorithm. Currently, the only valid value is: RSA_OAEP - - The plaintext column encryption key. - Encrypts a column encryption key using the certificate with the specified key path and using the specified algorithm. The format of the key path should be - "Local Machine/My/<certificate_thumbprint>" or "Current User/My/<certificate_thumbprint>". - - Returns -. The encrypted column encryption key. - To be added. - - - The provider name. - To be added. - - - The column master key path. - - -to indicate that the column master key supports enclave computations; otherwise, -. - Digitally signs the column master key metadata with the column master key referenced by the -parameter. - The signature of the column master key metadata. - To be added. - - - The complete path of an asymmetric key. The path format is specific to a key store provider. - A Boolean that indicates if this key can be sent to the trusted enclave. - The master key metadata siognature. - This function must be implemented by the corresponding Key Store providers. This function should use an asymmetric key identified by a key path and verify the masterkey metadata consisting of (masterKeyPath, allowEnclaveComputations, providerName). - A Boolean value that indicates if the master key metadata can be verified based on the provided signature. - To be added. - - - \ No newline at end of file + + + + The implementation of the key store provider for Windows Certificate Store. This class enables using certificates stored in the Windows Certificate Store as column master keys. For details, see Always Encrypted. + + + + + Key store provider for Windows Certificate Store. + + + + + The master key path. + + + The encryption algorithm. Currently, the only valid value is: RSA_OAEP + + + The encrypted column encryption key. + + + Decrypts the specified encrypted value of a column encryption key. The encrypted value is expected to be encrypted using the certificate with the specified key path and using the specified algorithm. The format of the key path should be "Local Machine/My/<certificate_thumbprint>" or "Current User/My/<certificate_thumbprint>". + + + Returns . The decrypted column encryption key. + + + + + The master key path. + + + The encryption algorithm. Currently, the only valid value is: RSA_OAEP + + + The plaintext column encryption key. + + + Encrypts a column encryption key using the certificate with the specified key path and using the specified algorithm. The format of the key path should be "Local Machine/My/<certificate_thumbprint>" or "Current User/My/<certificate_thumbprint>". + + + Returns . The encrypted column encryption key. + + + + + The provider name. + + + + + The column master key path. + + + to indicate that the column master key supports enclave computations; otherwise, . + + + Digitally signs the column master key metadata with the column master key referenced by the parameter. + + + The signature of the column master key metadata. + + + + + The complete path of an asymmetric key. The path format is specific to a key store provider. + + + A Boolean that indicates if this key can be sent to the trusted enclave. + + + The master key metadata signature. + + + This function must be implemented by the corresponding Key Store providers. This function should use an asymmetric key identified by a key path and verify the masterkey metadata consisting of (masterKeyPath, allowEnclaveComputations, providerName). + + + A Boolean value that indicates if the master key metadata can be verified based on the provided signature. + + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionCngProvider.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionCngProvider.xml index 30d0640781..d4db77f1a3 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionCngProvider.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionCngProvider.xml @@ -1,67 +1,90 @@ - - - The CMK Store provider implementation for using the Microsoft Cryptography API: Next Generation (CNG) with - Always Encrypted. - - - - - - - Initializes a new instance of the class. - To be added. - - - The master key path. - The encryption algorithm. - The encrypted column encryption key. - Decrypts the given encrypted value using an asymmetric key specified by the key path and the specified algorithm. The key path will be in the format of [ProviderName]/KeyIdentifier - and should be an asymmetric key stored in the specified CNG key store provider. The valid algorithm used to encrypt/decrypt the CEK is 'RSA_OAEP'. - - The decrypted column encryption key. - To be added. - - - The master key path. - The encryption algorithm. - The plaintext column encryption key. - Encrypts the given plain text column encryption key using an asymmetric key specified by the key path and the specified algorithm. The key path will be in the format of [ProviderName]/KeyIdentifier and should be an asymmetric key stored in the specified CNG key store provider. The valid algorithm used to encrypt/decrypt the CEK is 'RSA_OAEP'. - The encrypted column encryption key. - To be added. - - - A constant string for the provider name 'MSSQL_CNG_STORE'. - To be added. - - - The column master key path. The path format is specific to a key store provider. - to indicate that the column master key supports enclave computations; otherwise, . - Throws a exception in all cases. - The signature of the column master key metadata. - - method must be implemented by the corresponding key store providers. - should use an asymmetric key identified by a key path and sign the masterkey metadata consisting - of `masterKeyPath`, `allowEnclaveComputations`, and providerName. - - ]]> - - - - The complete path of an asymmetric key. The path format is specific to a key store provider. - A Boolean that indicates if this key can be sent to the trusted enclave. - The master key metadata signature. - This function must be implemented by the corresponding Key Store providers. This function should use an asymmetric key identified by a key path and verify the masterkey metadata consisting of (masterKeyPath, allowEnclaveComputations, providerName). - A Boolean that indicates if the master key metadata can be verified based on the provided signature. - To be added. - - + + + + The CMK Store provider implementation for using the Microsoft Cryptography API: Next Generation (CNG) with Always Encrypted. + + + Enables storing Always Encrypted column master key keys in a store, such as a hardware security module (HSM), that supports the Microsoft Cryptography API: Next Generation (CNG). + + + + + Initializes a new instance of the class. + + + + + The master key path. + + + The encryption algorithm. + + + The encrypted column encryption key. + + + Decrypts the given encrypted value using an asymmetric key specified by the key path and the specified algorithm. The key path will be in the format of [ProviderName]/KeyIdentifier and should be an asymmetric key stored in the specified CNG key store provider. The valid algorithm used to encrypt/decrypt the CEK is RSA_OAEP. + + + The decrypted column encryption key. + + + + + The master key path. + + + The encryption algorithm. + + + The plaintext column encryption key. + + + Encrypts the given plain text column encryption key using an asymmetric key specified by the key path and the specified algorithm. The key path will be in the format of [ProviderName]/KeyIdentifier and should be an asymmetric key stored in the specified CNG key store provider. The valid algorithm used to encrypt/decrypt the CEK is RSA_OAEP. + + + The encrypted column encryption key. + + + + + A constant string for the provider name MSSQL_CNG_STORE>. + + + + + The column master key path. The path format is specific to a key store provider. + + + to indicate that the column master key supports enclave computations; otherwise, . + + + Throws a exception in all cases. + + + The signature of the column master key metadata. + + + The method must be implemented by the corresponding key store providers. should use an asymmetric key identified by a key path and sign the master key metadata consisting of , , and . + + + + + The complete path of an asymmetric key. The path format is specific to a key store provider. + + + A Boolean that indicates if this key can be sent to the trusted enclave. + + + The master key metadata signature. + + + This function must be implemented by the corresponding Key Store providers. This function should use an asymmetric key identified by a key path and verify the master key metadata consisting of (masterKeyPath, allowEnclaveComputations, providerName). + + + A Boolean that indicates if the master key metadata can be verified based on the provided signature. + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionCspProvider.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionCspProvider.xml index 9e360781be..21bddf73b2 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionCspProvider.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionCspProvider.xml @@ -1,65 +1,90 @@ - - - The CMK Store provider implementation for using Microsoft CAPI based Cryptographic Service Providers (CSP) with - Always Encrypted. - - - - - - - Initializes a new instance of the class. - To be added. - - - The master key path. - The encryption algorithm. - The encrypted column encryption key. - Decrypts the given encrypted value using an asymmetric key specified by the key path and algorithm. The key path will be in the format of [ProviderName]/KeyIdentifier and should be an asymmetric key stored in the specified CSP provider. The valid algorithm used to encrypt/decrypt the CEK is 'RSA_OAEP'. - The decrypted column encryption key. - To be added. - - - The master key path. - The encryption algorithm. - The plaintext column encryption key. - Encrypts the given plain text column encryption key using an asymmetric key specified by the key path and the specified algorithm. The key path will be in the format of [ProviderName]/KeyIdentifier and should be an asymmetric key stored in the specified CSP provider. The valid algorithm used to encrypt/decrypt the CEK is 'RSA_OAEP'. - The encrypted column encryption key. - To be added. - - - A constant string for the provider name 'MSSQL_CSP_PROVIDER'. - To be added. - - - The column master key path. The path format is specific to a key store provider. - to indicate that the column master key supports enclave computations; otherwise, . - Throws a exception in all cases. - The signature of the column master key metadata. - - method must be implemented by the corresponding key store providers. - should use an asymmetric key identified by a key path and sign the masterkey metadata -consisting of `masterKeyPath`, `allowEnclaveComputations`, and providerName. - -]]> - - - - The complete path of an asymmetric key. The path format is specific to a key store provider. - A boolean that indicates if this key can be sent to the trusted enclave. - Master key metadata signature. - This function must be implemented by the corresponding Key Store providers. This function should use an asymmetric key identified by a key path and sign the masterkey metadata consisting of (masterKeyPath, allowEnclaveComputations, providerName). - A Boolean that indicates if the master key metadata can be verified based on the provided signature. - To be added. - - + + + + The CMK Store provider implementation for using Microsoft CAPI based Cryptographic Service Providers (CSP) with Always Encrypted. + + + Enables storing Always Encrypted column master key keys in a store, such as a hardware security module (HSM), that supports the Microsoft CAPI based Cryptographic Service Providers (CSP). + + + + + Initializes a new instance of the class. + + + + + The master key path. + + + The encryption algorithm. + + + The encrypted column encryption key. + + + Decrypts the given encrypted value using an asymmetric key specified by the key path and algorithm. The key path will be in the format of [ProviderName]/KeyIdentifier and should be an asymmetric key stored in the specified CSP provider. The valid algorithm used to encrypt/decrypt the CEK is RSA_OAEP'. + + + The decrypted column encryption key. + + + + + The master key path. + + + The encryption algorithm. + + + The plaintext column encryption key. + + + Encrypts the given plain text column encryption key using an asymmetric key specified by the key path and the specified algorithm. The key path will be in the format of [ProviderName]/KeyIdentifier and should be an asymmetric key stored in the specified CSP provider. The valid algorithm used to encrypt/decrypt the CEK is RSA_OAEP. + + + The encrypted column encryption key. + + + + + A constant string for the provider name MSSQL_CSP_PROVIDER. + + + + + The column master key path. The path format is specific to a key store provider. + + + to indicate that the column master key supports enclave computations; otherwise, . + + + Throws a exception in all cases. + + + The signature of the column master key metadata. + + + The method must be implemented by the corresponding key store providers. should use an asymmetric key identified by a key path and sign the master key metadata consisting of , , and . + + + + + The complete path of an asymmetric key. The path format is specific to a key store provider. + + + A boolean that indicates if this key can be sent to the trusted enclave. + + + Master key metadata signature. + + + This function must be implemented by the corresponding Key Store providers. This function should use an asymmetric key identified by a key path and sign the masterkey metadata consisting of (, , ). + + + A Boolean that indicates if the master key metadata can be verified based on the provided signature. + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionEnclaveProvider.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionEnclaveProvider.xml index dfbdbe8782..4276c98b9f 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionEnclaveProvider.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionEnclaveProvider.xml @@ -1,57 +1,97 @@ - - - The base class that defines the interface for enclave providers for Always Encrypted. - - - - - - Initializes a new instance of the class - To be added. - - - The information the provider uses to attest the enclave and generate a symmetric key for the session. The format of this information is specific to the enclave attestation protocol. - A Diffie-Hellman algorithm object that encapsulates a client-side key pair. - The set of parameters required for an enclave session. - The set of extra data needed for attesting the enclave. - The length of the extra data needed for attesting the enclave. - The requested enclave session or if the provider doesn't implement session caching. - A counter that the enclave provider is expected to increment each time SqlClient retrieves the session from the cache. The purpose of this field is to prevent replay attacks. - When overridden in a derived class, performs enclave attestation, generates a symmetric key for the session, creates a an enclave session and stores the session information in the cache. - To be added. - - - The endpoint of an attestation service for attesting the enclave. - A set of extra data needed for attesting the enclave. - The length of the extra data needed for attesting the enclave. - Gets the information that SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave. - The information SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave. - To be added. - - - The set of parameters required for enclave session. - to indicate that a set of extra data needs to be generated for attestation; otherwise, . - Indicates if this is a retry from a failed call. - When this method returns, the requested enclave session or if the provider doesn't implement session caching. This parameter is treated as uninitialized. - A counter that the enclave provider is expected to increment each time SqlClient retrieves the session from the cache. The purpose of this field is to prevent replay attacks. - A set of extra data needed for attesting the enclave. - The length of the extra data needed for attesting the enclave. - When overridden in a derived class, looks up an existing enclave session information in the enclave session cache. If the enclave provider doesn't implement enclave session caching, this method is expected to return in the parameter. - - To be added. - - - The set of parameters required for enclave session. - The session to be invalidated. - When overridden in a derived class, looks up and evicts an enclave session from the enclave session cache, if the provider implements session caching. - To be added. - - + + + + The base class that defines the interface for enclave providers for Always Encrypted. + + + An enclave is a protected region of memory inside SQL Server, used for computations on encrypted columns. An enclave provider encapsulates the client-side implementation details of the enclave attestation protocol as well as the logic for creating and caching enclave sessions. + + + + + Initializes a new instance of the class + + + + + The information the provider uses to attest the enclave and generate a symmetric key for the session. The format of this information is specific to the enclave attestation protocol. + + + A Diffie-Hellman algorithm object that encapsulates a client-side key pair. + + + The set of parameters required for an enclave session. + + + The set of extra data needed for attesting the enclave. + + + The length of the extra data needed for attesting the enclave. + + + The requested enclave session or if the provider doesn't implement session caching. + + + A counter that the enclave provider is expected to increment each time SqlClient retrieves the session from the cache. The purpose of this field is to prevent replay attacks. + + + When overridden in a derived class, performs enclave attestation, generates a symmetric key for the session, creates an enclave session and stores the session information in the cache. + + + + + The endpoint of an attestation service for attesting the enclave. + + + A set of extra data needed for attesting the enclave. + + + The length of the extra data needed for attesting the enclave. + + + Gets the information that SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave. + + + The information SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave. + + + + + The set of parameters required for enclave session. + + + to indicate that a set of extra data needs to be generated for attestation; otherwise, . + + + Indicates if this is a retry from a failed call. + + + When this method returns, the requested enclave session or if the provider doesn't implement session caching. This parameter is treated as uninitialized. + + + A counter that the enclave provider is expected to increment each time SqlClient retrieves the session from the cache. The purpose of this field is to prevent replay attacks. + + + A set of extra data needed for attesting the enclave. + + + The length of the extra data needed for attesting the enclave. + + + When overridden in a derived class, looks up an existing enclave session information in the enclave session cache. If the enclave provider doesn't implement enclave session caching, this method is expected to return in the parameter. + + + + + The set of parameters required for enclave session. + + + The session to be invalidated. + + + When overridden in a derived class, looks up and evicts an enclave session from the enclave session cache, if the provider implements session caching. + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionKeyStoreProvider.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionKeyStoreProvider.xml index 7c2dc715fd..8d57587c77 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionKeyStoreProvider.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionKeyStoreProvider.xml @@ -1,74 +1,103 @@ - - - Base class for all key store providers. A custom provider must derive from this class and override its member functions and then register it using - , - or - . - For details see, Always Encrypted. - - - - Initializes a new instance of the SqlColumnEncryptionKeyStoreProviderClass. - To be added. - - - The master key path. - The encryption algorithm. - The encrypted column encryption key. - Decrypts the specified encrypted value of a column encryption key. The encrypted value is expected to be encrypted using the column master key with the specified key path and using the specified algorithm. - - Returns . The decrypted column encryption key. - To be added. - - - The master key path. - The encryption algorithm. - The plaintext column encryption key. - Encrypts a column encryption key using the column master key with the specified key path and using the specified algorithm. - Returns . The encrypted column encryption key. - To be added. - - - The column master key path. - to indicate that the column master key supports enclave computations; otherwise, . - When implemented in a derived class, digitally signs the column master key metadata with the column master key referenced by the parameter. The input values used to generate the signature should be the specified values of the and parameters. - - The signature of the column master key metadata. - - method doesn't break applications that rely on an old API, it throws a - exception by default. - -The method will be used by client tools that generate Column Master Keys (CMK) for customers. - must be implemented by the corresponding key store providers that wish to use enclaves with -[Always Encrypted](https://docs.microsoft.com/sql/relational-databases/security/encryption/always-encrypted-database-engine). - -]]> - - In all cases. - - - The column master key path. - Indicates whether the column master key supports enclave computations. - The signature of the column master key metadata. - When implemented in a derived class, this method is expected to verify the specified signature is valid for the column master key with the specified key path and the specified enclave behavior. The default implementation throws NotImplementedException. - When implemented in a derived class, the method is expected to return true if the specified signature is valid, or false if the specified signature is not valid. The default implementation throws NotImplementedException. - To be added. - - - Gets or sets the lifespan of the decrypted column encryption key in the cache. Once the timespan has elapsed, the decrypted column encryption key is discarded and must be revalidated. - - . Any caching implementation should reference the value of this property before caching a column encryption key and not cache it if the value is zero. This will avoid duplicate caching and possible user confusion when they are trying to configure key caching. - ]]> - - - + + + + Base class for all key store providers. A custom provider must derive from this class and override its member functions and then register it using , or . For details see, Always Encrypted. + + + + + Initializes a new instance of the . + + + + + The master key path. + + + The encryption algorithm. + + + The encrypted column encryption key. + + + Decrypts the specified encrypted value of a column encryption key. The encrypted value is expected to be encrypted using the column master key with the specified key path and using the specified algorithm. + + + Returns . The decrypted column encryption key. + + + + + The master key path. + + + The encryption algorithm. + + + The plaintext column encryption key. + + + Encrypts a column encryption key using the column master key with the specified key path and using the specified algorithm. + + + Returns . The encrypted column encryption key. + + + + + The column master key path. + + + to indicate that the column master key supports enclave computations; otherwise, . + + + When implemented in a derived class, digitally signs the column master key metadata with the column master key referenced by the parameter. The input values used to generate the signature should be the specified values of the and parameters. + + + The signature of the column master key metadata. + + + + To ensure that the method doesn't break applications that rely on an old API, it throws a exception by default. + + + The method will be used by client tools that generate Column Master Keys (CMK) for customers. must be implemented by the corresponding key store providers that wish to use enclaves with Always Encrypted. + + + + In all cases. + + + + + The column master key path. + + + Indicates whether the column master key supports enclave computations. + + + The signature of the column master key metadata. + + + When implemented in a derived class, this method is expected to verify the specified signature is valid for the column master key with the specified key path and the specified enclave behavior. The default implementation throws NotImplementedException. + + + When implemented in a derived class, the method is expected to return true if the specified signature is valid, or false if the specified signature is not valid. The default implementation throws NotImplementedException. + + + + + Gets or sets the lifespan of the decrypted column encryption key in the cache. Once the timespan has elapsed, the decrypted column encryption key is discarded and must be revalidated. + + + + Internally, there is a cache of column encryption keys (once they are decrypted). This is useful for rapidly decrypting multiple data values. The default value is 2 hours. Setting this value to zero disables caching. + + + The column encryption keys decrypted by custom key store providers registered on a connection or command instance will not be cached. Custom key store providers should implement their own caching mechanism. Caching implemented by custom key store providers will be disabled by the driver if the key store provider instance is registered using . Any caching implementation should reference the value of this property before caching a column encryption key and not cache it if the value is zero. This will avoid duplicate caching and possible user confusion when they are trying to configure key caching. + + + + diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml index 7b0b19f031..18af6be796 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml @@ -1,3108 +1,4330 @@ - - - - Represents a Transact-SQL statement or stored procedure to execute against a SQL Server database. This class cannot be inherited. - - - is created, the read/write properties are set to their initial values. For a list of these values, see the constructor. - - features the following methods for executing commands at a SQL Server database: - -|Item|Description| -|----------|-----------------| -||Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this , generally executing commands such as INSERT, DELETE, UPDATE, and SET statements. Each call to must be paired with a call to which finishes the operation, typically on a separate thread.| -||Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this and retrieves one or more results sets from the server. Each call to must be paired with a call to which finishes the operation, typically on a separate thread.| -||Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this . Each call to `BeginExecuteXmlReader` must be paired with a call to `EndExecuteXmlReader`, which finishes the operation, typically on a separate thread, and returns an object.| -||Executes commands that return rows. For increased performance, invokes commands using the Transact-SQL `sp_executesql` system stored procedure. Therefore, might not have the effect that you want if used to execute commands such as Transact-SQL SET statements.| -||Executes commands such as Transact-SQL INSERT, DELETE, UPDATE, and SET statements.| -||Retrieves a single value (for example, an aggregate value) from a database.| -||Sends the to the and builds an object.| - -You can reset the property and reuse the object. However, you must close the before you can execute a new or previous command. - -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. - -> [!NOTE] -> Nameless, also called ordinal, parameters are not supported by the .NET Framework Data Provider for SQL Server. - -## Examples -The following example creates a , a , and a . The example reads through the data, writing it to the console. Finally, the example closes the and then the as it exits the `Using` code blocks. - -[!code-csharp[SqlCommand Example#1](~/../sqlclient/doc/samples/SqlCommand.cs#1)] - -The following sample shows how to create and execute different types of SqlCommand objects. - -First you must create the sample database, by executing the following script: - -[!code-sql[Setup Database](~/../sqlclient/doc/samples/SqlCommand_Setup.sql#1)] - -Next, compile and execute the following: - -[!code-csharp[SqlCommand Example#2](~/../sqlclient/doc/samples/SqlCommand_Intro.cs#1)] -]]> - - - - - Initializes a new instance of the - - class. - - - . - -|Properties|Initial value| -|----------------|-------------------| -||empty string ("")| -||30| -||`CommandType.Text`| -||Null| - -You can change the value for any of these properties through a separate call to the property. - - - -## Examples -The following example creates a and sets the `CommandTimeout` property. - -[!code-csharp[Classic WebData IDbCommand_CommandTimeout.cs](~/../sqlclient/doc/samples/IDbCommand_CommandTimeout.cs)] -]]> - - - - - The text of the query. - - - Initializes a new instance of the - - class with the text of the query. - - - is created, the following read/write properties are set to initial values. - -|Properties|Initial value| -|----------------|-------------------| -||`cmdText`| -||30| -||`CommandType.Text`| -||null| - -You can change the value for any of these properties through a separate call to the property. - -## Examples -The following example creates a , passing in the connection string and command text. - -[!code-csharp[SqlCommand_SqlCommand1](~/../sqlclient/doc/samples/SqlCommand_SqlCommand1.cs#1)] -]]> - - - - - The text of the query. - - - A - - that represents the connection to an instance of SQL Server. - - - Initializes a new instance of the - - class with the text of the query and a - - . - - - . - -|Properties|Initial value| -|----------------|-------------------| -||`cmdText`| -||30| -||`CommandType.Text`| -||A new that is the value for the `connection` parameter.| - -You can change the value for any of these parameters by setting the related property. - -## Examples -The following example creates a and sets some of its properties. - -[!code-csharp[SqlCommand_SqlCommand2.cs](~/../sqlclient/doc/samples/SqlCommand_SqlCommand2.cs#1)] -]]> - - - - - The text of the query. - - - A - - that represents the connection to an instance of SQL Server. - - - The - - in which the - - executes. - - - Initializes a new instance of the - - class with the text of the query, a - - , and the - - . - - - . - -|Properties|Initial value| -|----------------|-------------------| -||`cmdText`| -||30| -||`CommandType.Text`| -||A new that is the value for the `connection` parameter.| - -You can change the value for any of these parameters by setting the related property. -]]> - - - - - The text of the query. - - - A - - that represents the connection to an instance of SQL Server. - - - The - - in which the - - executes. - - - The encryption setting. For more information, see [Always Encrypted](/sql/relational-databases/security/encryption/always-encrypted-database-engine). - - - Initializes a new instance of the - - class with specified command text, connection, transaction, and encryption setting. - - - To be added. - - - - - Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this - - . - - - An - - that can be used to poll or wait for results, or both; this value is also needed when invoking - - , which returns the number of affected rows. - - - method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that does not return rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. - -Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. - -Because this overload does not support a callback procedure, developers must either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned . - -This method ignores the property. - - -## Examples -The following console application creates updates data within the **AdventureWorks** sample database, doing its work asynchronously. In order to emulate a long-running process, this example inserts a WAITFOR statement in the command text. Normally, you would not take efforts to make your commands run slower, but doing this in this case makes it easier to demonstrate the asynchronous behavior. - -[!code-csharp[SqlCommand_BeginExecuteNonQuery](~/../sqlclient/doc/samples/SqlCommand_BeginExecuteNonQuery.cs)] -]]> - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - Any error that occurred while executing the command text. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - or - - - - is set to true and a parameter with direction Output or InputOutput has been added to the collection. - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - An - - delegate that is invoked when the command's execution has completed. Pass - - ( - - in Microsoft Visual Basic) to indicate that no callback is required. - - - A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback procedure using the - - property. - - - Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this - - , given a callback procedure and state information. - - - An - - that can be used to poll or wait for results, or both; this value is also needed when invoking - - , which returns the number of affected rows. - - - method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that does not return rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. - -The `callback` parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the `asyncStateObject` parameter, and your callback procedure can retrieve this information using the property. - -Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. - -Because the callback procedure executes from within a background thread supplied by the Microsoft .NET common language runtime, it is very important that you take a rigorous approach to handling cross-thread interactions from within your applications. For example, you must not interact with a form's contents from within your callback procedure; should you have to update the form, you must switch back to the form's thread in order to do your work. The example in this topic demonstrates this behavior. - -All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure. - -This method ignores the property. - -## Examples -The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of several seconds (emulating a long-running command). - -This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called. - -To set up this example, create a new Windows application. Put a control and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment. - -[!code-csharp[DataWorks SqlCommand_BeginExecuteNonQueryForm#1](~/../sqlclient/doc/samples/SqlCommand_BeginExecuteNonQueryForm.cs)] -]]> - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - Any error that occurred while executing the command text. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - or - - - - is set to true and a parameter with direction Output or InputOutput has been added to the collection. - - - - - Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this - - , and retrieves one or more result sets from the server. - - - An - - that can be used to poll or wait for results, or both; this value is also needed when invoking - - , which returns a - - instance that can be used to retrieve the returned rows. - - - method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. - -Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks. - -Because this overload does not support a callback procedure, developers must either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned . - -If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. - -This method ignores the property. - - -## Examples -The following console application starts the process of retrieving a data reader asynchronously. While waiting for the results, this simple application sits in a loop, investigating the property value. As soon as the process has completed, the code retrieves the and displays its contents. - -[!code-csharp[SqlCommand_BeginExecuteReader#1](~/../sqlclient/doc/samples/SqlCommand_BeginExecuteReader.cs)] -]]> - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - Any error that occurred while executing the command text. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - or - - - - is set to true and a parameter with direction Output or InputOutput has been added to the collection. - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - One of the - - values, indicating options for statement execution and data retrieval. - - - Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this - - using one of the - - values. - - - An - - that can be used to poll, wait for results, or both; this value is also needed when invoking - - , which returns a - - instance that can be used to retrieve the returned rows. - - - method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. - -The `behavior` parameter lets you specify options that control the behavior of the command and its connection. These values can be combined together (using the programming language's `OR` operator); generally, developers use the `CommandBehavior.CloseConnection` value to make sure that the connection is closed by the runtime when the is closed. - -Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks. - -Because this overload does not support a callback procedure, developers must either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned . - -If you use or to access XML data, SQL Server returns any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. - -This method ignores the property. - - -## Examples -The following console application starts the process of retrieving a data reader asynchronously. While waiting for the results, this simple application sits in a loop, investigating the property value. Once the process has completed, the code retrieves the and displays its contents. - -This example also passes the `CommandBehavior.CloseConnection` and `CommandBehavior.SingleRow` values in the behavior parameter, causing the connection to be closed with the returned is closed, and to optimize for a single row result. - -[!code-csharp[SqlCommand_BeginExecuteReaderAsyncSimple](~/../sqlclient/doc/samples/SqlCommand_BeginExecuteReaderAsyncSimple.cs)] -]]> - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - Any error that occurred while executing the command text. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - or - - - - is set to true and a parameter with direction Output or InputOutput has been added to the collection. - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - An - - delegate that is invoked when the command's execution has completed. Pass - - ( - - in Microsoft Visual Basic) to indicate that no callback is required. - - - A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback procedure using the - - property. - - - Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this - - and retrieves one or more result sets from the server, given a callback procedure and state information. - - - An - - that can be used to poll, wait for results, or both; this value is also needed when invoking - - , which returns a - - instance which can be used to retrieve the returned rows. - - - method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed cause the object to block until the execution is finished. - -The `callback` parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the `stateObject` parameter, and your callback procedure can retrieve this information using the property. - -Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks. - -Because the callback procedure executes from within a background thread supplied by the Microsoft .NET runtime, it is very important that you take a rigorous approach to handling cross-thread interactions from within your applications. For example, you must not interact with a form's contents from within your callback procedure; should you have to update the form, you must switch back to the form's thread in order to do your work. The example in this topic demonstrates this behavior. - -All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure. - -If you use or to access XML data, SQL Server returns any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. - -This method ignores the property. - - -## Examples -The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of a few seconds (emulating a long-running command). Because the sample executes the command asynchronously, the form remains responsive while awaiting the results. This example passes the executing object as the `stateObject` parameter; doing so makes it simple to retrieve the object from within the callback procedure, so that the code can call the method corresponding to the initial call to . - -This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called. - -To set up this example, create a new Windows application. Put a control, a control, and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment. - -[!code-csharp[SqlCommand_BeginExecuteReaderAsync.cs](~/../sqlclient/doc/samples/SqlCommand_BeginExecuteReaderAsync.cs)] -]]> - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - Any error that occurred while executing the command text. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - or - - - - is set to true and a parameter with direction Output or InputOutput has been added to the collection. - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - An - - delegate that is invoked when the command's execution has completed. Pass - - ( - - in Microsoft Visual Basic) to indicate that no callback is required. - - - A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback procedure using the - - property. - - - One of the - - values, indicating options for statement execution and data retrieval. - - - Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this - - , using one of the - - values, and retrieving one or more result sets from the server, given a callback procedure and state information. - - - An - - that can be used to poll or wait for results, or both; this value is also needed when invoking - - , which returns a - - instance which can be used to retrieve the returned rows. - - - method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. - -The `callback` parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the `stateObject` parameter, and your callback procedure can retrieve this information using the property. - -The `behavior` parameter lets you specify options that control the behavior of the command and its connection. These values can be combined together (using the programming language's `Or` operator); generally, developers use the `CloseConnection` value to make sure that the connection is closed by the runtime when the is closed. Developers can also optimize the behavior of the by specifying the `SingleRow` value when it is known in advance that the Transact-SQL statement or stored procedure only returns a single row. - -Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks. - -Because the callback procedure executes from within a background thread supplied by the Microsoft .NET common language runtime, it is very important that you take a rigorous approach to handling cross-thread interactions from within your applications. For example, you must not interact with a form's contents from within your callback procedure--should you have to update the form, you must switch back to the form's thread in order to do your work. The example in this topic demonstrates this behavior. - -All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure. - -If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. - -This method ignores the property. - - -## Examples -The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of a few seconds (emulating a long-running command). Because the sample executes the command asynchronously, the form remains responsive while awaiting the results. This example passes the executing object as the `stateObject` parameter; doing so makes it simple to retrieve the object from within the callback procedure, so that the code can call the method corresponding to the initial call to . - -This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called. - -To set up this example, create a new Windows application. Put a control, a control, and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment. - -This example passes the `CommandBehavior.CloseConnection` value in the `behavior` parameter, causing the returned to automatically close its connection when it is closed. - -[!code-csharp[SqlCommand_BeginExecuteReaderAsyncBehavior](~/../sqlclient/doc/samples/SqlCommand_BeginExecuteReaderAsyncBehavior.cs)] -]]> - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - Any error that occurred while executing the command text. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - or - - - - is set to true and a parameter with direction Output or InputOutput has been added to the collection. - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this - - and returns results as an - - object. - - - An - - that can be used to poll or wait for results, or both; this value is also needed when invoking - - , which returns a single XML value. - - - method starts the process of asynchronously executing a Transact-SQL statement that returns rows as XML, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the `EndExecuteXmlReader` method to finish the operation and retrieve the XML returned by the command. The method returns immediately, but until the code executes the corresponding `EndExecuteXmlReader` method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the `EndExecuteXmlReader` before the command's execution is completed causes the object to block until the execution is finished. - -The property ordinarily specifies a Transact-SQL statement with a valid FOR XML clause. However, `CommandText` can also specify a statement that returns `ntext` data that contains valid XML. - -A typical query can be formatted as in the following C# example: - -```csharp -SqlCommand command = new SqlCommand("SELECT ContactID, FirstName, LastName FROM dbo.Contact FOR XML AUTO, XMLDATA", SqlConn); -``` - -This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the `EndExecuteXmlReader` method attaches the to the value on the first row, and discards the rest of the result set. - -The multiple active result set (MARS) feature lets multiple actions use the same connection. - -Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. - -Because this overload does not support a callback procedure, developers need to either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned . - -If you use or to access XML data, SQL Server returns any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. - -This method ignores the property. - - -## Examples -The following console application starts the process of retrieving XML data asynchronously. While waiting for the results, this simple application sits in a loop, investigating the property value. Once the process has completed, the code retrieves the XML and displays its contents. - -[!code-csharp[SqlCommand_BeginExecuteXmlReader#1]((~/../sqlclient/doc/samples/SqlCommand_BeginExecuteXmlReader.cs)] -]]> - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - Any error that occurred while executing the command text. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - or - - - - is set to true and a parameter with direction Output or InputOutput has been added to the collection. - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - An - - delegate that is invoked when the command's execution has completed. Pass - - ( - - in Microsoft Visual Basic) to indicate that no callback is required. - - - A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback procedure using the - - property. - - - Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this - - and returns results as an - - object, using a callback procedure. - - - An - - that can be used to poll, wait for results, or both; this value is also needed when the - - is called, which returns the results of the command as XML. - - - method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows as XML, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the requested XML data. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. - -The property ordinarily specifies a Transact-SQL statement with a valid FOR XML clause. However, `CommandText` can also specify a statement that returns data that contains valid XML. This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the method attaches the to the value on the first row, and discards the rest of the result set. - -A typical query can be formatted as in the following C# example: - -```csharp -SqlCommand command = new SqlCommand("SELECT ContactID, FirstName, LastName FROM Contact FOR XML AUTO, XMLDATA", SqlConn); -``` - -This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the method attaches the to the value on the first row, and discards the rest of the result set. - -The multiple active result set (MARS) feature lets multiple actions use the same connection. - -The `callback` parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the `stateObject` parameter, and your callback procedure can retrieve this information using the property. - -Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters is sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. - -All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure. - -If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. - -This method ignores the property. - - -## Examples -The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of a few seconds (emulating a long-running command). This example passes the executing object as the `stateObject` parameter--doing so makes it simple to retrieve the object from within the callback procedure, so that the code can call the method corresponding to the initial call to . - -This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called. - -To set up this example, create a new Windows application. Put a control, a control, and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment. - -[!code-csharp[SqlCommand_BeginExecuteXmlReaderAsync](~/../sqlclient/doc/samples/SqlCommand_BeginExecuteXmlReaderAsync.cs)] -]]> - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - Any error that occurred while executing the command text. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - or - - - - is set to true and a parameter with direction Output or InputOutput has been added to the collection. - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - - - Tries to cancel the execution of a - - . - - - , then call (implicitly or explicitly) before calling , and then call , the cancel command will not be sent to SQL Server and the result set can continue to stream after you call . To avoid this, make sure that you call before closing the reader or connection. - - -## Examples -The following example demonstrates the use of the method. - -[!code-csharp[SqlCommand_Cancel](~/../sqlclient/doc/samples/SqlCommand_Cancel.cs)] -]]> - - - - - Creates a new - - object that is a copy of the current instance. - - - A new - - object that is a copy of this instance. - - - To be added. - - - - - Gets the column encryption setting for this command. - - - The column encryption setting for this command. - - - - - Gets or sets the Transact-SQL statement, table name or stored procedure to execute at the data source. - - - The Transact-SQL statement or stored procedure to execute. The default is an empty string. - - - property is set to `StoredProcedure`, the property should be set to the name of the stored procedure. The user may be required to use escape character syntax if the stored procedure name contains any special characters. The command executes this stored procedure when you call one of the `Execute` methods. - -The Microsoft .NET Framework Data Provider for SQL Server does not support the question mark (?) placeholder for passing parameters to a Transact-SQL statement or a stored procedure called by a command of `CommandType.Text`. In this case, named parameters must be used. For example: - -```sql -SELECT * FROM dbo.Customers WHERE CustomerID = @CustomerID -``` - -For more information, see [Configuring parameters](/sql/connect/ado-net/configure-parameters). - -## Examples -The following example creates a and sets some of its properties. - -[!code-csharp[SqlCommand_CommandText](~/../sqlclient/doc/samples/SqlCommand_CommandText.cs)] -]]> - - - - - Gets or sets the 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. - - - [!NOTE] -> The property will be ignored during old-style asynchronous method calls such as . It will be honored by the newer async methods such as . - -> [!NOTE] -> This property is the cumulative time-out (for all network packets that are read during the invocation of a method) for all network reads during command execution or processing of the results. A time-out can still occur after the first row is returned, and does not include user processing time, only network read time. - -For example, with a 30 second time out, if requires two network packets, then it has 30 seconds to read both network packets. If you call again, it will have another 30 seconds to read any data that it requires. - -[!code-csharp[SqlCommand CommandTimeout](~/../sqlclient/doc/samples/SqlCommand_CommandTimeout.cs)] -]]> - - The value set is less than 0. - - - - Gets or sets a value indicating how the - - property is to be interpreted. - - - One of the - - values. The default is - - . - - - property to `StoredProcedure`, you should set the property to the name of the stored procedure. The command executes this stored procedure when you call one of the Execute methods. - -The Microsoft .NET Framework Data Provider for SQL Server does not support the question mark (?) placeholder for passing parameters to a SQL Statement or a stored procedure called with a of . In this case, named parameters must be used. For example: - -SELECT * FROM Customers WHERE CustomerID = @CustomerID - -For more information, see [Configuring parameters](/sql/connect/ado-net/configure-parameters). - -## Examples -The following example creates a and sets some of its properties. - -[!code-csharp[IDbCommand_CommandTimeout](~/../sqlclient/doc/samples/IDbCommand_CommandTimeout.cs)] -]]> - - - - - Gets or sets the - - used by this instance of the - - . - - - The connection to a data source. The default value is - - . - - - . - -If the property is not null and the transaction has already been committed or rolled back, is set to null. - - - -## Examples -The following example creates a and sets some of its properties. - -[!code-csharp[SqlCommand_Connection](~/../sqlclient/doc/samples/SqlCommand_Connection.cs)] -]]> - - - The - - property was changed while the command was enlisted in a transaction. - - - - - To be added. - - - To be added. - - - To be added. - - - - - Creates a new instance of a - - object. - - - A - - object. - - - method is a strongly-typed version of . -]]> - - - - - To be added. - - - To be added. - - - To be added. - - - - - Gets the collection of objects. - - - The parameters of the SQL statement or stored procedure. - - - To be added. - - - - - To be added. - - - To be added. - - - To be added. - - - - - Gets or sets a value indicating whether the command object should be visible in a Windows Form Designer control. - - - A value indicating whether the command object should be visible in a control. The default is - - . - - - To be added. - - - - - To be added. - - - To be added. - - - To be added. - - + + + + Represents a Transact-SQL statement or stored procedure to execute against a SQL Server database. This class cannot be inherited. + + + + When an instance of is created, the read/write properties are set to their initial values. For a list of these values, see the constructor. + + + features the following methods for executing commands at a SQL Server database: + + + + Item + Description + + + + + Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this , generally executing commands such as INSERT, DELETE, UPDATE, and SET statements. Each call to must be paired with a call to which finishes the operation, typically on a separate thread. + + + + + + Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this and retrieves one or more results sets from the server. Each call to must be paired with a call to which finishes the operation, typically on a separate thread. + + + + + + Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this . Each call to must be paired with a call to , which finishes the operation, typically on a separate thread, and returns an object. + + + + + + Executes commands that return rows. For increased performance, invokes commands using the Transact-SQL sp_executesql system stored procedure. Therefore, might not have the effect that you want if used to execute commands such as Transact-SQL SET statements. + + + + + Executes commands such as Transact-SQL INSERT, DELETE, UPDATE, and SET statements. + + + + Retrieves a single value (for example, an aggregate value) from a database. + + + + + Sends the to the and builds an object. + + + + + + You can reset the property and reuse the object. However, you must close the before you can execute a new or previous command. + + + 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. + + + + Nameless, also called ordinal, parameters are not supported by the .NET Framework Data Provider for SQL Server. + + + + + + The following example creates a , a , and a . The example reads through the data, writing it to the console. Finally, the example closes the and then the as it exits the using code blocks. + + + + 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"; + ReadOrderData(str); + } + + private static void ReadOrderData(string connectionString) + { + string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;"; + using (SqlConnection connection = new SqlConnection(connectionString)) + { + SqlCommand command = new SqlCommand(queryString, connection); + connection.Open(); + using (SqlDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1])); + } + } + } + } + } + } + + + + The following sample shows how to create and execute different types of SqlCommand objects. + + + + USE [master] + GO + + CREATE DATABASE [MySchool] + GO + + USE [MySchool] + GO + + SET ANSI_NULLS ON + GO + SET QUOTED_IDENTIFIER ON + GO + CREATE procedure [dbo].[CourseExtInfo] @CourseId int + as + select c.CourseID,c.Title,c.Credits,d.Name as DepartmentName + from Course as c left outer join Department as d on c.DepartmentID=d.DepartmentID + where c.CourseID=@CourseId + + GO + + SET ANSI_NULLS ON + GO + SET QUOTED_IDENTIFIER ON + GO + create procedure [dbo].[DepartmentInfo] @DepartmentId int,@CourseCount int output + as + select @CourseCount=Count(c.CourseID) + from course as c + where c.DepartmentID=@DepartmentId + + select d.DepartmentID,d.Name,d.Budget,d.StartDate,d.Administrator + from Department as d + where d.DepartmentID=@DepartmentId + + GO + + SET ANSI_NULLS ON + GO + SET QUOTED_IDENTIFIER ON + GO + Create PROCEDURE [dbo].[GetDepartmentsOfSpecifiedYear] + @Year int,@BudgetSum money output + AS + BEGIN + SELECT @BudgetSum=SUM([Budget]) + FROM [MySchool].[dbo].[Department] + Where YEAR([StartDate])=@Year + + SELECT [DepartmentID] + ,[Name] + ,[Budget] + ,[StartDate] + ,[Administrator] + FROM [MySchool].[dbo].[Department] + Where YEAR([StartDate])=@Year + + END + 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 + + 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 + + SET ANSI_NULLS ON + GO + SET QUOTED_IDENTIFIER ON + GO + CREATE TABLE [dbo].[Person]([PersonID] [int] IDENTITY(1,1) NOT NULL, + [LastName] [nvarchar](50) NOT NULL, + [FirstName] [nvarchar](50) NOT NULL, + [HireDate] [datetime] NULL, + [EnrollmentDate] [datetime] NULL, + CONSTRAINT [PK_School.Student] PRIMARY KEY CLUSTERED + ( + [PersonID] 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 + CREATE TABLE [dbo].[StudentGrade]([EnrollmentID] [int] IDENTITY(1,1) NOT NULL, + [CourseID] [nvarchar](10) NOT NULL, + [StudentID] [int] NOT NULL, + [Grade] [decimal](3, 2) NOT NULL, + CONSTRAINT [PK_StudentGrade] PRIMARY KEY CLUSTERED + ( + [EnrollmentID] 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 + create view [dbo].[EnglishCourse] + as + select c.CourseID,c.Title,c.Credits,c.DepartmentID + from Course as c join Department as d on c.DepartmentID=d.DepartmentID + where d.Name=N'English' + + 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 + SET IDENTITY_INSERT [dbo].[Person] ON + + INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (1, N'Hu', N'Nan', NULL, CAST(0x0000A0BF00000000 AS DateTime)) + INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (2, N'Norman', N'Laura', NULL, CAST(0x0000A0BF00000000 AS DateTime)) + INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (3, N'Olivotto', N'Nino', NULL, CAST(0x0000A0BF00000000 AS DateTime)) + INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (4, N'Anand', N'Arturo', NULL, CAST(0x0000A0BF00000000 AS DateTime)) + INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (5, N'Jai', N'Damien', NULL, CAST(0x0000A0BF00000000 AS DateTime)) + INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (6, N'Holt', N'Roger', CAST(0x000097F100000000 AS DateTime), NULL) + INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (7, N'Martin', N'Randall', CAST(0x00008B1A00000000 AS DateTime), NULL) + SET IDENTITY_INSERT [dbo].[Person] OFF + SET IDENTITY_INSERT [dbo].[StudentGrade] ON + + INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (1, N'C1045', 1, CAST(3.50 AS Decimal(3, 2))) + INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (2, N'C1045', 2, CAST(3.00 AS Decimal(3, 2))) + INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (3, N'C1045', 3, CAST(2.50 AS Decimal(3, 2))) + INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (4, N'C1045', 4, CAST(4.00 AS Decimal(3, 2))) + INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (5, N'C1045', 5, CAST(3.50 AS Decimal(3, 2))) + INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (6, N'C1061', 1, CAST(4.00 AS Decimal(3, 2))) + INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (7, N'C1061', 3, CAST(3.50 AS Decimal(3, 2))) + INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (8, N'C1061', 4, CAST(2.50 AS Decimal(3, 2))) + INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (9, N'C1061', 5, CAST(1.50 AS Decimal(3, 2))) + INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (10, N'C2021', 1, CAST(2.50 AS Decimal(3, 2))) + INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (11, N'C2021', 2, CAST(3.50 AS Decimal(3, 2))) + INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (12, N'C2021', 4, CAST(3.00 AS Decimal(3, 2))) + INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (13, N'C2021', 5, CAST(3.00 AS Decimal(3, 2))) + INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (14, N'C2042', 1, CAST(2.00 AS Decimal(3, 2))) + INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (15, N'C2042', 2, CAST(3.50 AS Decimal(3, 2))) + INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (16, N'C2042', 3, CAST(4.00 AS Decimal(3, 2))) + INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (17, N'C2042', 5, CAST(3.00 AS Decimal(3, 2))) + SET IDENTITY_INSERT [dbo].[StudentGrade] 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 + ALTER TABLE [dbo].[StudentGrade] WITH CHECK ADD CONSTRAINT [FK_StudentGrade_Student] FOREIGN KEY([StudentID]) + REFERENCES [dbo].[Person] ([PersonID]) + GO + ALTER TABLE [dbo].[StudentGrade] CHECK CONSTRAINT [FK_StudentGrade_Student] + GO + + + Next, compile and execute the following: + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + using System.Threading.Tasks; + + class Program + { + static class SqlHelper + { + // Set the connection, command, and then execute the command with non query. + public static Int32 ExecuteNonQuery(String connectionString, String commandText, + CommandType commandType, params SqlParameter[] parameters) + { + using (SqlConnection conn = new SqlConnection(connectionString)) + { + using (SqlCommand cmd = new SqlCommand(commandText, conn)) + { + // There are three command types: StoredProcedure, Text, TableDirect. The TableDirect + // type is only for OLE DB. + cmd.CommandType = commandType; + cmd.Parameters.AddRange(parameters); + + conn.Open(); + return cmd.ExecuteNonQuery(); + } + } + } + + // Set the connection, command, and then execute the command and only return one value. + public static Object ExecuteScalar(String connectionString, String commandText, + CommandType commandType, params SqlParameter[] parameters) + { + using (SqlConnection conn = new SqlConnection(connectionString)) + { + using (SqlCommand cmd = new SqlCommand(commandText, conn)) + { + cmd.CommandType = commandType; + cmd.Parameters.AddRange(parameters); + + conn.Open(); + return cmd.ExecuteScalar(); + } + } + } + + // Set the connection, command, and then execute the command with query and return the reader. + public static SqlDataReader ExecuteReader(String connectionString, String commandText, + CommandType commandType, params SqlParameter[] parameters) + { + SqlConnection conn = new SqlConnection(connectionString); + + using (SqlCommand cmd = new SqlCommand(commandText, conn)) + { + cmd.CommandType = commandType; + cmd.Parameters.AddRange(parameters); + + conn.Open(); + // When using CommandBehavior.CloseConnection, the connection will be closed when the + // IDataReader is closed. + SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); + + return reader; + } + } + } + + static void Main(string[] args) + { + String connectionString = "Data Source=(local);Initial Catalog=MySchool;Integrated Security=True;"; + + CountCourses(connectionString, 2012); + Console.WriteLine(); + + Console.WriteLine("Following result is the departments that started from 2007:"); + GetDepartments(connectionString, 2007); + Console.WriteLine(); + + Console.WriteLine("Add the credits when the credits of course are lower than 4."); + AddCredits(connectionString, 4); + Console.WriteLine(); + + Console.WriteLine("Please press any key to exit..."); + Console.ReadKey(); + } + + static void CountCourses(String connectionString, Int32 year) + { + String commandText = "Select Count([CourseID]) FROM [MySchool].[dbo].[Course] Where Year=@Year"; + SqlParameter parameterYear = new SqlParameter("@Year", SqlDbType.Int); + parameterYear.Value = year; + + Object oValue = SqlHelper.ExecuteScalar(connectionString, commandText, CommandType.Text, parameterYear); + Int32 count; + if (Int32.TryParse(oValue.ToString(), out count)) + { + Console.WriteLine("There {0} {1} course{2} in {3}.", count > 1 ? "are" : "is", count, count > 1 ? "s" : null, year); + } + } + + // Display the Departments that start from the specified year. + static void GetDepartments(String connectionString, Int32 year) + { + String commandText = "dbo.GetDepartmentsOfSpecifiedYear"; + + // Specify the year of StartDate + SqlParameter parameterYear = new SqlParameter("@Year", SqlDbType.Int); + parameterYear.Value = year; + + // When the direction of parameter is set as Output, you can get the value after + // executing the command. + SqlParameter parameterBudget = new SqlParameter("@BudgetSum", SqlDbType.Money); + parameterBudget.Direction = ParameterDirection.Output; + + using (SqlDataReader reader = SqlHelper.ExecuteReader(connectionString, commandText, + CommandType.StoredProcedure, parameterYear, parameterBudget)) + { + Console.WriteLine("{0,-20}{1,-20}{2,-20}{3,-20}", "Name", "Budget", "StartDate", + "Administrator"); + while (reader.Read()) + { + Console.WriteLine("{0,-20}{1,-20:C}{2,-20:d}{3,-20}", reader["Name"], + reader["Budget"], reader["StartDate"], reader["Administrator"]); + } + } + Console.WriteLine("{0,-20}{1,-20:C}", "Sum:", parameterBudget.Value); + } + + // If credits of course is lower than the certain value, the method will add the credits. + static void AddCredits(String connectionString, Int32 creditsLow) + { + String commandText = "Update [MySchool].[dbo].[Course] Set Credits=Credits+1 Where Credits<@Credits"; + + SqlParameter parameterCredits = new SqlParameter("@Credits", creditsLow); + + Int32 rows = SqlHelper.ExecuteNonQuery(connectionString, commandText, CommandType.Text, parameterCredits); + + Console.WriteLine("{0} row{1} {2} updated.", rows, rows > 1 ? "s" : null, rows > 1 ? "are" : "is"); + } + } + + + + + + Initializes a new instance of the class. + + + + The base constructor initializes all fields to their default values. The following table shows initial property values for an instance of . + + + + + Properties + Initial value + + + + empty string ("") + + + + 30 + + + + + + + + + + + + + You can change the value for any of these properties through a separate call to the property. + + + + + The following example creates a and sets the property. + + + + using System; + using System.Xml; + using System.Data; + using System.Data.Common; + using System.Windows.Forms; + using Microsoft.Data.SqlClient; + + public class Form1 : Form + { + protected DataSet DataSet1; + protected DataGrid dataGrid1; + + public void CreateSqlCommand() + { + SqlCommand command = new SqlCommand(); + command.CommandTimeout = 15; + command.CommandType = CommandType.Text; + } + } + + + + + + The text of the query. + + + Initializes a new instance of the class with the text of the query. + + + + When an instance of is created, the following read/write properties are set to initial values. + + + + + Properties + Initial value + + + + + + + + 30 + + + + + + + + + + + + + You can change the value for any of these properties through a separate call to the property. + + + + + The following example creates a , passing in the connection string and command text. + + + + using System; + using System.Xml; + using System.Data; + using System.Data.Common; + using System.Windows.Forms; + using Microsoft.Data.SqlClient; + + public class Form1 : Form + { + protected DataSet DataSet1; + protected DataGrid dataGrid1; + + public void CreateCommand() + { + string queryString = "SELECT * FROM Categories ORDER BY CategoryID"; + SqlCommand command = new SqlCommand(queryString); + command.CommandTimeout = 15; + command.CommandType = CommandType.Text; + } + } + + + + + + The text of the query. + + + A that represents the connection to an instance of SQL Server. + + + Initializes a new instance of the class with the text of the query and a . + + + + The following table shows initial property values for an instance of . + + + + + Properties + Initial value + + + + cmdText + + + + 30 + + + + + + + + + A new that is the value for the parameter. + + + + + + You can change the value for any of these parameters by setting the related property. + + + + + The following example creates a and sets some of its properties. + + + + 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); + connection.Open(); + SqlDataReader reader = command.ExecuteReader(); + while (reader.Read()) + { + Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1])); + } + } + } + } + } + + + + + + The text of the query. + + + A that represents the connection to an instance of SQL Server. + + + The in which the executes. + + + Initializes a new instance of the class with the text of the query, a , and the . + + + + The following table shows initial property values for an instance of . + + + + + Properties + Initial value + + + + cmdText + + + + 30 + + + + + + + + + A new that is the value for the parameter. + + + + + + You can change the value for any of these parameters by setting the related property. + + + + + + The text of the query. + + + A that represents the connection to an instance of SQL Server. + + + The in which the executes. + + + The encryption setting. For more information, see Always Encrypted. + + + Initializes a new instance of the class with specified command text, connection, transaction, and encryption setting. + + + + + Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this . + + + An that can be used to poll or wait for results, or both; this value is also needed when invoking , which returns the number of affected rows. + + + + The method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that does not return rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. + + + Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server - that is, reads are asynchronous. + + + Because this overload does not support a callback procedure, developers must either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned . + + + This method ignores the property. + + + + + The following console application creates updates data within the AdventureWorks sample database, doing its work asynchronously. In order to emulate a long-running process, this example inserts a WAITFOR statement in the command text. Normally, you would not take efforts to make your commands run slower, but doing this in this case makes it easier to demonstrate the asynchronous behavior. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Class1 + { + static void Main() + { + // This is a simple example that demonstrates the usage of the + // BeginExecuteNonQuery functionality. + // The WAITFOR statement simply adds enough time to prove the + // asynchronous nature of the command. + + string commandText = + "UPDATE Production.Product SET ReorderPoint = ReorderPoint + 1 " + + "WHERE ReorderPoint Is Not Null;" + + "WAITFOR DELAY '0:0:3';" + + "UPDATE Production.Product SET ReorderPoint = ReorderPoint - 1 " + + "WHERE ReorderPoint Is Not Null"; + + RunCommandAsynchronously(commandText, GetConnectionString()); + + Console.WriteLine("Press ENTER to continue."); + Console.ReadLine(); + } + + private static void RunCommandAsynchronously(string commandText, string connectionString) + { + // Given command text and connection string, asynchronously execute + // the specified command against the connection. For this example, + // the code displays an indicator as it is working, verifying the + // asynchronous behavior. + using (SqlConnection connection = new SqlConnection(connectionString)) + { + try + { + int count = 0; + SqlCommand command = new SqlCommand(commandText, connection); + connection.Open(); + + IAsyncResult result = command.BeginExecuteNonQuery(); + while (!result.IsCompleted) + { + Console.WriteLine("Waiting ({0})", count++); + // Wait for 1/10 second, so the counter + // does not consume all available resources + // on the main thread. + System.Threading.Thread.Sleep(100); + } + + Console.WriteLine("Command complete. Affected {0} rows.", + command.EndExecuteNonQuery(result)); + } + catch (SqlException ex) + { + Console.WriteLine("Error ({0}): {1}", ex.Number, ex.Message); + } + catch (InvalidOperationException ex) + { + Console.WriteLine("Error: {0}", ex.Message); + } + catch (Exception ex) + { + // You might want to pass these errors + // back out to the caller. + Console.WriteLine("Error: {0}", ex.Message); + } + } + } + + private static string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local);Integrated Security=SSPI;" + + "Initial Catalog=AdventureWorks"; + } + } + + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + + + Any error that occurred while executing the command text. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + is set to true and a parameter with direction Output or InputOutput has been added to the collection. + + + + + An error occurred in a , or object during a streaming operation For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + An delegate that is invoked when the command's execution has completed. Pass ( in Microsoft Visual Basic) to indicate that no callback is required. + + + A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback procedure using the property. + + + Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this , given a callback procedure and state information. + + + An that can be used to poll or wait for results, or both; this value is also needed when invoking , which returns the number of affected rows. + + + + The method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that does not return rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. + + + The parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the parameter, and your callback procedure can retrieve this information using the property. + + + Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. + + + Because the callback procedure executes from within a background thread supplied by the Microsoft .NET common language runtime, it is very important that you take a rigorous approach to handling cross-thread interactions from within your applications. For example, you must not interact with a form's contents from within your callback procedure; should you have to update the form, you must switch back to the form's thread in order to do your work. The example in this topic demonstrates this behavior. + + + All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure. + + + This method ignores the property. + + + + + The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of several seconds (emulating a long-running command). + + + This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called. + + + To set up this example, create a new Windows application. Put a control and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment. + + + + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Data; + using System.Drawing; + using System.Text; + using System.Windows.Forms; + using Microsoft.Data.SqlClient; + + namespace Microsoft.AdoDotNet.CodeSamples + { + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + + // Hook up the form's Load event handler (you can double-click on + // the form's design surface in Visual Studio), and then add + // this code to the form's class: + private void Form1_Load(object sender, EventArgs e) + { + this.button1.Click += new System.EventHandler(this.button1_Click); + this.FormClosing += new System.Windows.Forms. + FormClosingEventHandler(this.Form1_FormClosing); + } + + // You need this delegate in order to display text from a thread + // other than the form's thread. See the HandleCallback + // procedure for more information. + // This same delegate matches both the DisplayStatus + // and DisplayResults methods. + private delegate void DisplayInfoDelegate(string Text); + + // This flag ensures that the user does not attempt + // to restart the command or close the form while the + // asynchronous command is executing. + private bool isExecuting; + + // This example maintains the connection object + // externally, so that it is available for closing. + private SqlConnection connection; + + private static string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local);Integrated Security=true;" + + "Initial Catalog=AdventureWorks"; + } + + private void DisplayStatus(string Text) + { + this.label1.Text = Text; + } + + private void DisplayResults(string Text) + { + this.label1.Text = Text; + DisplayStatus("Ready"); + } + + private void Form1_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e) + { + if (isExecuting) + { + MessageBox.Show(this, "Cannot close the form until " + + "the pending asynchronous command has completed. Please wait..."); + e.Cancel = true; + } + } + + private void button1_Click(object sender, System.EventArgs e) + { + if (isExecuting) + { + MessageBox.Show(this, + "Already executing. Please wait until the current query " + + "has completed."); + } + else + { + SqlCommand command = null; + try + { + DisplayResults(""); + DisplayStatus("Connecting..."); + connection = new SqlConnection(GetConnectionString()); + // To emulate a long-running query, wait for + // a few seconds before working with the data. + // This command does not do much, but that's the point-- + // it does not change your data, in the long run. + string commandText = + "WAITFOR DELAY '0:0:05';" + + "UPDATE Production.Product SET ReorderPoint = ReorderPoint + 1 " + + "WHERE ReorderPoint Is Not Null;" + + "UPDATE Production.Product SET ReorderPoint = ReorderPoint - 1 " + + "WHERE ReorderPoint Is Not Null"; + + command = new SqlCommand(commandText, connection); + connection.Open(); + + DisplayStatus("Executing..."); + isExecuting = true; + // Although it is not required that you pass the + // SqlCommand object as the second parameter in the + // BeginExecuteNonQuery call, doing so makes it easier + // to call EndExecuteNonQuery in the callback procedure. + AsyncCallback callback = new AsyncCallback(HandleCallback); + command.BeginExecuteNonQuery(callback, command); + + } + catch (Exception ex) + { + isExecuting = false; + DisplayStatus(string.Format("Ready (last error: {0})", ex.Message)); + if (connection != null) + { + connection.Close(); + } + } + } + } + + private void HandleCallback(IAsyncResult result) + { + try + { + // Retrieve the original command object, passed + // to this procedure in the AsyncState property + // of the IAsyncResult parameter. + SqlCommand command = (SqlCommand)result.AsyncState; + int rowCount = command.EndExecuteNonQuery(result); + string rowText = " rows affected."; + if (rowCount == 1) + { + rowText = " row affected."; + } + + rowText = rowCount + rowText; + + // You may not interact with the form and its contents + // from a different thread, and this callback procedure + // is all but guaranteed to be running from a different thread + // than the form. Therefore you cannot simply call code that + // displays the results, like this: + // DisplayResults(rowText) + + // Instead, you must call the procedure from the form's thread. + // One simple way to accomplish this is to call the Invoke + // method of the form, which calls the delegate you supply + // from the form's thread. + DisplayInfoDelegate del = new DisplayInfoDelegate(DisplayResults); + this.Invoke(del, rowText); + + } + catch (Exception ex) + { + // Because you are now running code in a separate thread, + // if you do not handle the exception here, none of your other + // code catches the exception. Because none of + // your code is on the call stack in this thread, there is nothing + // higher up the stack to catch the exception if you do not + // handle it here. You can either log the exception or + // invoke a delegate (as in the non-error case in this + // example) to display the error on the form. In no case + // can you simply display the error without executing a delegate + // as in the try block here. + + // You can create the delegate instance as you + // invoke it, like this: + this.Invoke(new DisplayInfoDelegate(DisplayStatus), + String.Format("Ready(last error: {0}", ex.Message)); + } + finally + { + isExecuting = false; + if (connection != null) + { + connection.Close(); + } + } + } + } + } + + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + + + Any error that occurred while executing the command text. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + is set to true and a parameter with direction Output or InputOutput has been added to the collection. + + + + + + + Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this , and retrieves one or more result sets from the server. + + + An that can be used to poll or wait for results, or both; this value is also needed when invoking , which returns a instance that can be used to retrieve the returned rows. + + + + The method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. + + + Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server - that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks. + + + Because this overload does not support a callback procedure, developers must either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned . + + + If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. + + + This method ignores the property. + + + + + The following console application starts the process of retrieving a data reader asynchronously. While waiting for the results, this simple application sits in a loop, investigating the property value. As soon as the process has completed, the code retrieves the and displays its contents. + + + + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + + + Any error that occurred while executing the command text. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + is set to true and a parameter with direction Output or InputOutput has been added to the collection. + + + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + One of the values, indicating options for statement execution and data retrieval. + + + Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this using one of the values. + + + An that can be used to poll, wait for results, or both; this value is also needed when invoking , which returns a instance that can be used to retrieve the returned rows. + + + + The method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. + + + The behavior parameter lets you specify options that control the behavior of the command and its connection. These values can be combined (using the programming language's OR operator); generally, developers use the CommandBehavior.CloseConnection value to make sure that the connection is closed by the runtime when the is closed. + + + Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server - that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks. + + + Because this overload does not support a callback procedure, developers must either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned . + + + If you use or to access XML data, SQL Server returns any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. + + + This method ignores the property. + + + + + The following console application starts the process of retrieving a data reader asynchronously. While waiting for the results, this simple application sits in a loop, investigating the property value. Once the process has completed, the code retrieves the and displays its contents. + + + This example also passes the and values in the behavior parameter, causing the connection to be closed with the returned is closed, and to optimize for a single row result. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Class1 + { + static void Main() + { + // This example is not terribly useful, but it proves a point. + // The WAITFOR statement simply adds enough time to prove the + // asynchronous nature of the command. + string commandText = "WAITFOR DELAY '00:00:03';" + + "SELECT ProductID, Name FROM Production.Product WHERE ListPrice < 100"; + + RunCommandAsynchronously(commandText, GetConnectionString()); + + Console.WriteLine("Press ENTER to continue."); + Console.ReadLine(); + } + + private static void RunCommandAsynchronously(string commandText, string connectionString) + { + // Given command text and connection string, asynchronously execute + // the specified command against the connection. For this example, + // the code displays an indicator as it is working, verifying the + // asynchronous behavior. + try + { + // The code does not need to handle closing the connection explicitly-- + // the use of the CommandBehavior.CloseConnection option takes care + // of that for you. + SqlConnection connection = new SqlConnection(connectionString); + SqlCommand command = new SqlCommand(commandText, connection); + + connection.Open(); + IAsyncResult result = command.BeginExecuteReader(CommandBehavior.CloseConnection); + + // Although it is not necessary, the following code + // displays a counter in the console window, indicating that + // the main thread is not blocked while awaiting the command + // results. + int count = 0; + while (!result.IsCompleted) + { + Console.WriteLine("Waiting ({0})", count++); + // Wait for 1/10 second, so the counter + // does not consume all available resources + // on the main thread. + System.Threading.Thread.Sleep(100); + } + + using (SqlDataReader reader = command.EndExecuteReader(result)) + { + DisplayResults(reader); + } + } + catch (SqlException ex) + { + Console.WriteLine("Error ({0}): {1}", ex.Number, ex.Message); + } + catch (InvalidOperationException ex) + { + Console.WriteLine("Error: {0}", ex.Message); + } + catch (Exception ex) + { + // You might want to pass these errors + // back out to the caller. + Console.WriteLine("Error: {0}", ex.Message); + } + } + + private static void DisplayResults(SqlDataReader reader) + { + // Display the data within the reader. + while (reader.Read()) + { + // Display all the columns. + for (int i = 0; i < reader.FieldCount; i++) + { + Console.Write("{0}\t", reader.GetValue(i)); + } + + Console.WriteLine(); + } + } + + private static string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local);Integrated Security=true;" + + "Initial Catalog=AdventureWorks"; + } + } + + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + + + Any error that occurred while executing the command text. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + is set to true and a parameter with direction Output or InputOutput has been added to the collection. + + + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + An delegate that is invoked when the command's execution has completed. Pass ( in Microsoft Visual Basic) to indicate that no callback is required. + + + A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback procedure using the property. + + + Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this and retrieves one or more result sets from the server, given a callback procedure and state information. + + + An that can be used to poll, wait for results, or both; this value is also needed when invoking , which returns a instance which can be used to retrieve the returned rows. + + + + The method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed cause the object to block until the execution is finished. + + + The parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the parameter, and your callback procedure can retrieve this information using the property. + + + Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks. + + + Because the callback procedure executes from within a background thread supplied by the Microsoft .NET runtime, it is very important that you take a rigorous approach to handling cross-thread interactions from within your applications. For example, you must not interact with a form's contents from within your callback procedure; should you have to update the form, you must switch back to the form's thread in order to do your work. The example in this topic demonstrates this behavior. + + + All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure. + + + If you use or to access XML data, SQL Server returns any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. + + + This method ignores the property. + + + + + The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of a few seconds (emulating a long-running command). Because the sample executes the command asynchronously, the form remains responsive while awaiting the results. This example passes the executing object as the parameter; doing so makes it simple to retrieve the object from within the callback procedure, so that the code can call the method corresponding to the initial call to . + + + This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called. + + + To set up this example, create a new Windows application. Put a control, a control, and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Class1 + { + static void Main() + { + // This example is not terribly useful, but it proves a point. + // The WAITFOR statement simply adds enough time to prove the + // asynchronous nature of the command. + string commandText = "WAITFOR DELAY '00:00:03';" + + "SELECT ProductID, Name FROM Production.Product WHERE ListPrice < 100"; + + RunCommandAsynchronously(commandText, GetConnectionString()); + + Console.WriteLine("Press ENTER to continue."); + Console.ReadLine(); + } + + private static void RunCommandAsynchronously(string commandText, string connectionString) + { + // Given command text and connection string, asynchronously execute + // the specified command against the connection. For this example, + // the code displays an indicator as it is working, verifying the + // asynchronous behavior. + try + { + // The code does not need to handle closing the connection explicitly-- + // the use of the CommandBehavior.CloseConnection option takes care + // of that for you. + SqlConnection connection = new SqlConnection(connectionString); + SqlCommand command = new SqlCommand(commandText, connection); + + connection.Open(); + IAsyncResult result = command.BeginExecuteReader(CommandBehavior.CloseConnection); + + // Although it is not necessary, the following code + // displays a counter in the console window, indicating that + // the main thread is not blocked while awaiting the command + // results. + int count = 0; + while (!result.IsCompleted) + { + Console.WriteLine("Waiting ({0})", count++); + // Wait for 1/10 second, so the counter + // does not consume all available resources + // on the main thread. + System.Threading.Thread.Sleep(100); + } + + using (SqlDataReader reader = command.EndExecuteReader(result)) + { + DisplayResults(reader); + } + } + catch (SqlException ex) + { + Console.WriteLine("Error ({0}): {1}", ex.Number, ex.Message); + } + catch (InvalidOperationException ex) + { + Console.WriteLine("Error: {0}", ex.Message); + } + catch (Exception ex) + { + // You might want to pass these errors + // back out to the caller. + Console.WriteLine("Error: {0}", ex.Message); + } + } + + private static void DisplayResults(SqlDataReader reader) + { + // Display the data within the reader. + while (reader.Read()) + { + // Display all the columns. + for (int i = 0; i < reader.FieldCount; i++) + { + Console.Write("{0}\t", reader.GetValue(i)); + } + + Console.WriteLine(); + } + } + + private static string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local);Integrated Security=true;" + + "Initial Catalog=AdventureWorks"; + } + } + + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + + Any error that occurred while executing the command text. + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + is set to true and a parameter with direction Output or InputOutput has been added to the collection. + + + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + An delegate that is invoked when the command's execution has completed. Pass ( in Microsoft Visual Basic) to indicate that no callback is required. + + + A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback procedure using the property. + + + One of the values, indicating options for statement execution and data retrieval. + + + Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this , using one of the values, and retrieving one or more result sets from the server, given a callback procedure and state information. + + + An that can be used to poll or wait for results, or both; this value is also needed when invoking , which returns a instance which can be used to retrieve the returned rows. + + + + The method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. + + + The parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the stateObject parameter, and your callback procedure can retrieve this information using the property. + + + The parameter lets you specify options that control the behavior of the command and its connection. These values can be combined together (using the programming language's Or operator); generally, developers use the CloseConnection value to make sure that the connection is closed by the runtime when the is closed. Developers can also optimize the behavior of the by specifying the SingleRow value when it is known in advance that the Transact-SQL statement or stored procedure only returns a single row. + + + Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks. + + + Because the callback procedure executes from within a background thread supplied by the Microsoft .NET common language runtime, it is very important that you take a rigorous approach to handling cross-thread interactions from within your applications. For example, you must not interact with a form's contents from within your callback procedure--should you have to update the form, you must switch back to the form's thread in order to do your work. The example in this topic demonstrates this behavior. + + + All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure. + + + If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. + + + This method ignores the property. + + + + + The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of a few seconds (emulating a long-running command). Because the sample executes the command asynchronously, the form remains responsive while awaiting the results. This example passes the executing object as the stateObject parameter; doing so makes it simple to retrieve the object from within the callback procedure, so that the code can call the method corresponding to the initial call to . + + + This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called. + + + To set up this example, create a new Windows application. Put a control, a control, and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment. + + + This example passes the value in the parameter, causing the returned to automatically close its connection when it is closed. + + + + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Data; + using System.Drawing; + using System.Text; + using System.Windows.Forms; + using Microsoft.Data.SqlClient; + + namespace Microsoft.AdoDotNet.CodeSamples + { + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + + // Hook up the form's Load event handler (you can double-click on + // the form's design surface in Visual Studio), and then add + // this code to the form's class: + // You need this delegate in order to fill the grid from + // a thread other than the form's thread. See the HandleCallback + // procedure for more information. + private delegate void FillGridDelegate(SqlDataReader reader); + + // You need this delegate to update the status bar. + private delegate void DisplayStatusDelegate(string Text); + + // This flag ensures that the user does not attempt + // to restart the command or close the form while the + // asynchronous command is executing. + private bool isExecuting; + + private void DisplayStatus(string Text) + { + this.label1.Text = Text; + } + + private void FillGrid(SqlDataReader reader) + { + try + { + DataTable table = new DataTable(); + table.Load(reader); + this.dataGridView1.DataSource = table; + DisplayStatus("Ready"); + } + catch (Exception ex) + { + // Because you are guaranteed this procedure + // is running from within the form's thread, + // it can directly interact with members of the form. + DisplayStatus(string.Format("Ready (last attempt failed: {0})", ex.Message)); + } + finally + { + // Closing the reader also closes the connection, + // because this reader was created using the + // CommandBehavior.CloseConnection value. + if (reader != null) + { + reader.Close(); + } + } + } + + private void HandleCallback(IAsyncResult result) + { + try + { + // Retrieve the original command object, passed + // to this procedure in the AsyncState property + // of the IAsyncResult parameter. + SqlCommand command = (SqlCommand)result.AsyncState; + SqlDataReader reader = command.EndExecuteReader(result); + + // You may not interact with the form and its contents + // from a different thread, and this callback procedure + // is all but guaranteed to be running from a different thread + // than the form. Therefore you cannot simply call code that + // fills the grid, like this: + // FillGrid(reader); + // Instead, you must call the procedure from the form's thread. + // One simple way to accomplish this is to call the Invoke + // method of the form, which calls the delegate you supply + // from the form's thread. + FillGridDelegate del = new FillGridDelegate(FillGrid); + this.Invoke(del, reader); + + // Do not close the reader here, because it is being used in + // a separate thread. Instead, have the procedure you have + // called close the reader once it is done with it. + } + catch (Exception ex) + { + // Because you are now running code in a separate thread, + // if you do not handle the exception here, none of your other + // code catches the exception. Because there is none of + // your code on the call stack in this thread, there is nothing + // higher up the stack to catch the exception if you do not + // handle it here. You can either log the exception or + // invoke a delegate (as in the non-error case in this + // example) to display the error on the form. In no case + // can you simply display the error without executing a delegate + // as in the try block here. + // You can create the delegate instance as you + // invoke it, like this: + this.Invoke(new DisplayStatusDelegate(DisplayStatus), "Error: " + ex.Message); + } + finally + { + isExecuting = false; + } + } + + private string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local);Integrated Security=true;" + + "Initial Catalog=AdventureWorks"; + } + + private void button1_Click(object sender, System.EventArgs e) + { + if (isExecuting) + { + MessageBox.Show(this, + "Already executing. Please wait until the current query " + + "has completed."); + } + else + { + SqlCommand command = null; + SqlConnection connection = null; + try + { + DisplayStatus("Connecting..."); + connection = new SqlConnection(GetConnectionString()); + // To emulate a long-running query, wait for + // a few seconds before retrieving the real data. + command = new SqlCommand("WAITFOR DELAY '0:0:5';" + + "SELECT ProductID, Name, ListPrice, Weight FROM Production.Product", + connection); + connection.Open(); + + DisplayStatus("Executing..."); + isExecuting = true; + // Although it is not required that you pass the + // SqlCommand object as the second parameter in the + // BeginExecuteReader call, doing so makes it easier + // to call EndExecuteReader in the callback procedure. + AsyncCallback callback = new AsyncCallback(HandleCallback); + command.BeginExecuteReader(callback, command, + CommandBehavior.CloseConnection); + } + catch (Exception ex) + { + DisplayStatus("Error: " + ex.Message); + if (connection != null) + { + connection.Close(); + } + } + } + } + + private void Form1_Load(object sender, System.EventArgs e) + { + this.button1.Click += new System.EventHandler(this.button1_Click); + this.FormClosing += new FormClosingEventHandler(Form1_FormClosing); + } + + void Form1_FormClosing(object sender, FormClosingEventArgs e) + { + if (isExecuting) + { + MessageBox.Show(this, "Cannot close the form until " + + "the pending asynchronous command has completed. Please wait..."); + e.Cancel = true; + } + } + } + } + + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + + + Any error that occurred while executing the command text. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + is set to true and a parameter with direction Output or InputOutput has been added to the collection. + + + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this and returns results as an object. + + + An that can be used to poll or wait for results, or both; this value is also needed when invoking , which returns a single XML value. + + + + The method starts the process of asynchronously executing a Transact-SQL statement that returns rows as XML, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the XML returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the EndExecuteXmlReader before the command's execution is completed causes the object to block until the execution is finished. + + + The property ordinarily specifies a Transact-SQL statement with a valid FOR XML clause. However, CommandText can also specify a statement that returns ntext data that contains valid XML. + + + A typical query can be formatted as in the following C# example: + + + + SqlCommand command = new SqlCommand("SELECT ContactID, FirstName, LastName FROM dbo.Contact FOR XML AUTO, XMLDATA", SqlConn); + + + + This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the method attaches the to the value on the first row, and discards the rest of the result set. + + + The multiple active result set (MARS) feature lets multiple actions use the same connection. + + + Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. + + + Because this overload does not support a callback procedure, developers need to either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned . + + + If you use or to access XML data, SQL Server returns any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. + + + This method ignores the property. + + + + + The following console application starts the process of retrieving XML data asynchronously. While waiting for the results, this simple application sits in a loop, investigating the property value. Once the process has completed, the code retrieves the XML and displays its contents. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + using System.Xml; + + class Class1 + { + static void Main() + { + // This example is not terribly effective, but it proves a point. + // The WAITFOR statement simply adds enough time to prove the + // asynchronous nature of the command. + string commandText = + "WAITFOR DELAY '00:00:03';" + + "SELECT Name, ListPrice FROM Production.Product " + + "WHERE ListPrice < 100 " + + "FOR XML AUTO, XMLDATA"; + + RunCommandAsynchronously(commandText, GetConnectionString()); + + Console.WriteLine("Press ENTER to continue."); + Console.ReadLine(); + } + + private static void RunCommandAsynchronously(string commandText, string connectionString) + { + // Given command text and connection string, asynchronously execute + // the specified command against the connection. For this example, + // the code displays an indicator as it is working, verifying the + // asynchronous behavior. + using (SqlConnection connection = new SqlConnection(connectionString)) + { + SqlCommand command = new SqlCommand(commandText, connection); + + connection.Open(); + IAsyncResult result = command.BeginExecuteXmlReader(); + + // Although it is not necessary, the following procedure + // displays a counter in the console window, indicating that + // the main thread is not blocked while awaiting the command + // results. + int count = 0; + while (!result.IsCompleted) + { + Console.WriteLine("Waiting ({0})", count++); + // Wait for 1/10 second, so the counter + // does not consume all available resources + // on the main thread. + System.Threading.Thread.Sleep(100); + } + + XmlReader reader = command.EndExecuteXmlReader(result); + DisplayProductInfo(reader); + } + } + + private static void DisplayProductInfo(XmlReader reader) + { + // Display the data within the reader. + while (reader.Read()) + { + // Skip past items that are not from the correct table. + if (reader.LocalName.ToString() == "Production.Product") + { + Console.WriteLine("{0}: {1:C}", + reader["Name"], Convert.ToSingle(reader["ListPrice"])); + } + } + } + + private static string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local);Integrated Security=true;" + + "Initial Catalog=AdventureWorks"; + } + } + + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + + + Any error that occurred while executing the command text. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + is set to true and a parameter with direction Output or InputOutput has been added to the collection. + + + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + An delegate that is invoked when the command's execution has completed. Pass ( in Microsoft Visual Basic) to indicate that no callback is required. + + + A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback procedure using the property. + + + Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this and returns results as an object, using a callback procedure. + + + An that can be used to poll, wait for results, or both; this value is also needed when the is called, which returns the results of the command as XML. + + + + The method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows as XML, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the requested XML data. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished. + + + The property ordinarily specifies a Transact-SQL statement with a valid FOR XML clause. However, can also specify a statement that returns data that contains valid XML. This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the method attaches the to the value on the first row, and discards the rest of the result set. + + + A typical query can be formatted as in the following C# example: + + + + SqlCommand command = new SqlCommand("SELECT ContactID, FirstName, LastName FROM Contact FOR XML AUTO, XMLDATA", SqlConn); + + + + This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the method attaches the to the value on the first row, and discards the rest of the result set. + + + The multiple active result set (MARS) feature lets multiple actions use the same connection. + + + The parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the stateObject parameter, and your callback procedure can retrieve this information using the property. + + + Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters is sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. + + + All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure. + + + If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. + + + This method ignores the property. + + + + + The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of a few seconds (emulating a long-running command). This example passes the executing object as the parameter--doing so makes it simple to retrieve the object from within the callback procedure, so that the code can call the method corresponding to the initial call to . + + + To set up this example, create a new Windows application. Put a control, a control, and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment. + + + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Data; + using System.Drawing; + using System.Text; + using System.Windows.Forms; + using System.Xml; + using Microsoft.Data.SqlClient; + + namespace Microsoft.AdoDotNet.CodeSamples + { + public partial class Form1 : Form + { + // Hook up the form's Load event handler and then add + // this code to the form's class: + // You need these delegates in order to display text from a thread + // other than the form's thread. See the HandleCallback + // procedure for more information. + private delegate void DisplayInfoDelegate(string Text); + private delegate void DisplayReaderDelegate(XmlReader reader); + + private bool isExecuting; + + // This example maintains the connection object + // externally, so that it is available for closing. + private SqlConnection connection; + + public Form1() + { + InitializeComponent(); + } + + private string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local);Integrated Security=true;" + + "Initial Catalog=AdventureWorks"; + } + + private void DisplayStatus(string Text) + { + this.label1.Text = Text; + } + + private void ClearProductInfo() + { + // Clear the list box. + this.listBox1.Items.Clear(); + } + + private void DisplayProductInfo(XmlReader reader) + { + // Display the data within the reader. + while (reader.Read()) + { + // Skip past items that are not from the correct table. + if (reader.LocalName.ToString() == "Production.Product") + { + this.listBox1.Items.Add(String.Format("{0}: {1:C}", + reader["Name"], Convert.ToDecimal(reader["ListPrice"]))); + } + } + DisplayStatus("Ready"); + } + + private void Form1_FormClosing(object sender, + System.Windows.Forms.FormClosingEventArgs e) + { + if (isExecuting) + { + MessageBox.Show(this, "Cannot close the form until " + + "the pending asynchronous command has completed. Please wait..."); + e.Cancel = true; + } + } + + private void button1_Click(object sender, System.EventArgs e) + { + if (isExecuting) + { + MessageBox.Show(this, + "Already executing. Please wait until the current query " + + "has completed."); + } + else + { + SqlCommand command = null; + try + { + ClearProductInfo(); + DisplayStatus("Connecting..."); + connection = new SqlConnection(GetConnectionString()); + + // To emulate a long-running query, wait for + // a few seconds before working with the data. + string commandText = + "WAITFOR DELAY '00:00:03';" + + "SELECT Name, ListPrice FROM Production.Product " + + "WHERE ListPrice < 100 " + + "FOR XML AUTO, XMLDATA"; + + command = new SqlCommand(commandText, connection); + connection.Open(); + + DisplayStatus("Executing..."); + isExecuting = true; + // Although it is not required that you pass the + // SqlCommand object as the second parameter in the + // BeginExecuteXmlReader call, doing so makes it easier + // to call EndExecuteXmlReader in the callback procedure. + AsyncCallback callback = new AsyncCallback(HandleCallback); + command.BeginExecuteXmlReader(callback, command); + + } + catch (Exception ex) + { + isExecuting = false; + DisplayStatus(string.Format("Ready (last error: {0})", ex.Message)); + if (connection != null) + { + connection.Close(); + } + } + } + } + + private void HandleCallback(IAsyncResult result) + { + try + { + // Retrieve the original command object, passed + // to this procedure in the AsyncState property + // of the IAsyncResult parameter. + SqlCommand command = (SqlCommand)result.AsyncState; + XmlReader reader = command.EndExecuteXmlReader(result); + + // You may not interact with the form and its contents + // from a different thread, and this callback procedure + // is all but guaranteed to be running from a different thread + // than the form. + + // Instead, you must call the procedure from the form's thread. + // One simple way to accomplish this is to call the Invoke + // method of the form, which calls the delegate you supply + // from the form's thread. + DisplayReaderDelegate del = new DisplayReaderDelegate(DisplayProductInfo); + this.Invoke(del, reader); + + } + catch (Exception ex) + { + // Because you are now running code in a separate thread, + // if you do not handle the exception here, none of your other + // code catches the exception. Because none of + // your code is on the call stack in this thread, there is nothing + // higher up the stack to catch the exception if you do not + // handle it here. You can either log the exception or + // invoke a delegate (as in the non-error case in this + // example) to display the error on the form. In no case + // can you simply display the error without executing a delegate + // as in the try block here. + + // You can create the delegate instance as you + // invoke it, like this: + this.Invoke(new DisplayInfoDelegate(DisplayStatus), + String.Format("Ready(last error: {0}", ex.Message)); + } + finally + { + isExecuting = false; + if (connection != null) + { + connection.Close(); + } + } + } + + private void Form1_Load(object sender, System.EventArgs e) + { + this.button1.Click += new System.EventHandler(this.button1_Click); + this.FormClosing += new System.Windows.Forms. + FormClosingEventHandler(this.Form1_FormClosing); + } + } + } + + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + + + Any error that occurred while executing the command text. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + is set to true and a parameter with direction Output or InputOutput has been added to the collection. + + + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + Tries to cancel the execution of a . + + + + If there is nothing to cancel, nothing occurs. However, if there is a command in process, and the attempt to cancel fails, no exception is generated. + + + In some rare cases, if you call , then call (implicitly or explicitly) before calling , and then call , the cancel command will not be sent to SQL Server and the result set can continue to stream after you call . To avoid this, make sure that you call before closing the reader or connection. + + + + + The following example demonstrates the use of the method. + + + using System; + using System.Data; + using System.Threading; + using Microsoft.Data.SqlClient; + + class Program + { + private static SqlCommand m_rCommand; + + public static SqlCommand Command + { + get { return m_rCommand; } + set { m_rCommand = value; } + } + + public static void Thread_Cancel() + { + Command.Cancel(); + } + + static void Main() + { + string connectionString = GetConnectionString(); + try + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + + Command = connection.CreateCommand(); + Command.CommandText = "DROP TABLE TestCancel"; + try + { + Command.ExecuteNonQuery(); + } + catch { } + + Command.CommandText = "CREATE TABLE TestCancel(co1 int, co2 char(10))"; + Command.ExecuteNonQuery(); + Command.CommandText = "INSERT INTO TestCancel VALUES (1, '1')"; + Command.ExecuteNonQuery(); + + Command.CommandText = "SELECT * FROM TestCancel"; + SqlDataReader reader = Command.ExecuteReader(); + + Thread rThread2 = new Thread(new ThreadStart(Thread_Cancel)); + rThread2.Start(); + rThread2.Join(); + + reader.Read(); + System.Console.WriteLine(reader.FieldCount); + reader.Close(); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + static private string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local);Initial Catalog=AdventureWorks;" + + "Integrated Security=SSPI"; + } + } + + + + + + Creates a new object that is a copy of the current instance. + + + A new object that is a copy of this instance. + + + + + Gets the column encryption setting for this command. + + + The column encryption setting for this command. + + + + + Gets or sets the Transact-SQL statement, table name or stored procedure to execute at the data source. + + + The Transact-SQL statement or stored procedure to execute. The default is an empty string. + + + + When the property is set to , the property should be set to the name of the stored procedure. The user may be required to use escape character syntax if the stored procedure name contains any special characters. The command executes this stored procedure when you call one of the Execute* methods. + + + The Microsoft .NET Framework Data Provider for SQL Server does not support the question mark (?) placeholder for passing parameters to a Transact-SQL statement or a stored procedure called by a command of . In this case, named parameters must be used. For example: + + + + SELECT * FROM dbo.Customers WHERE CustomerID = @CustomerID + + + + For more information, see Configuring parameters. + + + + + The following example creates a and sets some of its properties. + + + + using System; + using System.Data; + using System.Data.Common; + using System.Windows.Forms; + using System.Xml; + using Microsoft.Data.SqlClient; + + public class Form1 : Form + { + protected DataSet DataSet1; + protected DataGrid dataGrid1; + + public void CreateCommand() + { + SqlCommand command = new SqlCommand(); + command.CommandText = "SELECT * FROM Categories ORDER BY CategoryID"; + command.CommandTimeout = 15; + command.CommandType = CommandType.Text; + } + } + + + + + + Gets or sets the 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. + + + + A value of 0 indicates no limit (an attempt to execute a command will wait indefinitely). + + + + The property will be ignored during old-style asynchronous method calls such as . It will be honored by the newer async methods such as . + + + + + This property is the cumulative time-out (for all network packets that are read during the invocation of a method) for all network reads during command execution or processing of the results. A time-out can still occur after the first row is returned, and does not include user processing time, only network read time. + + + + For example, with a 30 second time out, if requires two network packets, then it has 30 seconds to read both network packets. If you call again, it will have another 30 seconds to read any data that it requires. + + + + + + using System; + using Microsoft.Data.SqlClient; + + public class A + { + public static void Main() + { + string connectionString = "<Your-connection-string-here>"; + + // Wait for 5 second delay in the command + string queryString = "waitfor delay '00:00:05'"; + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + SqlCommand command = new SqlCommand(queryString, connection); + // Setting command timeout to 1 second + command.CommandTimeout = 1; + try + { + command.ExecuteNonQuery(); + } + catch (SqlException e) + { + Console.WriteLine("Got expected SqlException due to command timeout "); + Console.WriteLine(e); + } + } + } + } + + + + The value set is less than 0. + + + + + Gets or sets a value indicating how the property is to be interpreted. + + + One of the values. The default is . + + + + When you set the property to , you should set the property to the name of the stored procedure. The command executes this stored procedure when you call one of the Execute methods. + + + The Microsoft .NET Framework Data Provider for SQL Server does not support the question mark (?) placeholder for passing parameters to a SQL Statement or a stored procedure called with a of . In this case, named parameters must be used. For example: + + + SELECT * FROM Customers WHERE CustomerID = @CustomerID + + + For more information, see Configuring parameters. + + + + + The following example creates a and sets some of its properties. + + + + using System; + using System.Xml; + using System.Data; + using System.Data.Common; + using System.Windows.Forms; + using Microsoft.Data.SqlClient; + + public class Form1 : Form + { + protected DataSet DataSet1; + protected DataGrid dataGrid1; + + public void CreateSqlCommand() + { + SqlCommand command = new SqlCommand(); + command.CommandTimeout = 15; + command.CommandType = CommandType.Text; + } + } + + + + + + Gets or sets the used by this instance of the . + + + The connection to a data source. The default value is . + + + + If the command is enlisted in an existing transaction, and the connection is changed, trying to execute the command will throw an . + + + If the property is not null and the transaction has already been committed or rolled back, is set to null. + + + + + The following example creates a and sets some of its properties. + + + + 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(); + command.Connection = connection; + command.CommandTimeout = 15; + command.CommandType = CommandType.Text; + command.CommandText = queryString; + + connection.Open(); + SqlDataReader reader = command.ExecuteReader(); + while (reader.Read()) + { + Console.WriteLine(String.Format("{0}, {1}", + reader[0], reader[1])); + } + } + } + } + } + + + + The property was changed while the command was enlisted in a transaction. + + + + + To be added. + + + To be added. + + + To be added. + + + + + Creates a new instance of a object. + + + A object. + + + The method is a strongly-typed version of . + + + + + To be added. + + + To be added. + + + To be added. + + + + + Gets the collection of objects. + + + The parameters of the SQL statement or stored procedure. + + + + + To be added. + + + To be added. + + + To be added. + + + + + Gets or sets a value indicating whether the command object should be visible in a Windows Form Designer control. + + + A value indicating whether the command object should be visible in a control. The default is . + + + + + To be added. + + + To be added. + + + To be added. + + - Gets or sets a value indicating whether the command object should optimize parameter performance by disabling Output and InputOutput directions when submitting the command to the SQL Server.
- This option is only used when the is Text otherwise it is ignored. + Gets or sets a value indicating whether the command object should optimize parameter performance by disabling Output and InputOutput directions when submitting the command to the SQL Server.
This option is only used when the is otherwise it is ignored. +
+ + A value indicating whether the command object should optimize parameter performance by disabling Output and InputOuput parameter directions when submitting the command to the SQL Server. The default is . + + + + You must set the value for this property before the command is executed for it to take effect. + + + When a command is submitted to the server with parameters a list of the parameter names is sent as part of the submission. The list is used on the server to match Output and InputOutput parameters to the results of the query execution so that the values can be returned to the caller. This option disables the construction and submission of the parameter name list and as a consequence disables the use of Output and InputOutput parameters. The return parameter is not affected by this option. + + + A command sent with this option changes the way parameters are handled on the server, because there is no need to maintain an output parameter map. The result of this change is that queries with large numbers of input parameters may execute much faster. + + + The fewest number of parameters where this will take effect depends on the individual situation and should be detected by measuring query duration with and without the option enabled. Any query with more than 24 parameters may show lower overall query duration. Queries with parameter counts lower than 24 are unlikely to show a difference. + + + + If the option is enabled and a parameter with Direction Output or InputOutput is present in the Parameters collection an InvalidOperationException will be thrown when the command is executed. + + + +
+ + + The returned by the call to . + + + Finishes asynchronous execution of a Transact-SQL statement. + + + The number of rows affected (the same behavior as ). + + + When you call to execute a Transact-SQL statement, you must call in order to complete the operation. If the process of executing the command has not yet finished, this method blocks until the operation is complete. Users can verify that the command has completed its operation by using the instance returned by the method. If a callback procedure was specified in the call to , this method must be called. + + + For examples demonstrating the use of the method, see . + + + parameter is null ( in Microsoft Visual Basic) + + + was called more than once for a single command execution, or the method was mismatched against its execution method (for example, the code called to complete execution of a call to . + + + + + The amount of time specified in elapsed and the asynchronous operation specified with is not complete. + + + In some situations, can set incorrectly. If this occurs and is called, EndExecuteNonQuery could raise a SqlException error if the amount of time specified in elapsed and the asynchronous operation specified with is not complete. To correct this situation, you should either increase the value of CommandTimeout or reduce the work being done by the asynchronous operation. + + + + + + + The returned by the call to . + + + Finishes asynchronous execution of a Transact-SQL statement, returning the requested . + + + A object that can be used to retrieve the requested rows. + + + When you call to execute a Transact-SQL statement, you must call in order to complete the operation. If the process of executing the command has not yet finished, this method blocks until the operation is complete. Users can verify that the command has completed its operation by using the instance returned by the method. If a callback procedure was specified in the call to , this method must be called. + + + For examples demonstrating the use of the method, see . + + + parameter is null ( in Microsoft Visual Basic) + + + was called more than once for a single command execution, or the method was mismatched against its execution method (for example, the code called to complete execution of a call to . + + + + + The returned by the call to . + + + Finishes asynchronous execution of a Transact-SQL statement, returning the requested data as XML. + + + An object that can be used to fetch the resulting XML data. + + + When you call to execute a Transact-SQL statement, you must call in order to complete the operation. If the process of executing the command has not yet finished, this method blocks until the operation is complete. Users can verify that the command has completed its operation by using the instance returned by the method. If a callback procedure was specified in the call to , this method must be called. + + + For examples demonstrating the use of the method, see . + + + parameter is null ( in Microsoft Visual Basic) + + + was called more than once for a single command execution, or the method was mismatched against its execution method (for example, the code called to complete execution of a call to . + + + + + 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. + + + + + Executes a Transact-SQL statement against the connection and returns the number of rows affected. + + + The number of rows affected. + + + + You can use the to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a by executing UPDATE, INSERT, or DELETE statements. + + + Although the returns no rows, any output parameters or return values mapped to parameters are populated with data. + + + For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. When SET NOCOUNT ON is set on the connection (before or as part of executing the command, or as part of a trigger initiated by the execution of the command) the rows affected by individual statements stop contributing to the count of rows affected that is returned by this method. If no statements are detected that contribute to the count, the return value is -1. If a rollback occurs, the return value is also -1. + + + + + The following example creates a and then executes it using . The example is passed a string that is a Transact-SQL statement (such as UPDATE, INSERT, or DELETE) and a string to use to connect to the data source. + + + + 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(); + } + } + } + } + + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + + + An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + The cancellation instruction. + + + An asynchronous version of , which executes a Transact-SQL statement against the connection and returns the number of rows affected. The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. + + + A task representing the asynchronous operation. + + + + For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see Asynchronous Programming. + + + For long-running queries on the server, consider using due to a known issue with canceling queries via a cancellation token. Also, consider canceling execution using the method. + + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + + + Calling more than once for the same instance before task completion. + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + SQL Server returned an error while executing the command text. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + Sends the to the and builds a . + + + A object. + + + + When the property is set to , the property should be set to the name of the stored procedure. The command executes this stored procedure when you call . + + + If a transaction is deadlocked, an exception may not be thrown until is called. + + + The multiple active result set (MARS) feature allows for multiple actions using the same connection. + + + If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. + + + + + The following example creates a , and then executes it by passing a string that is a Transact-SQL SELECT statement, and a string to use to connect to the data source. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + 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)) + { + connection.Open(); + + SqlCommand command = new SqlCommand(queryString, connection); + SqlDataReader reader = command.ExecuteReader(); + while (reader.Read()) + { + Console.WriteLine(String.Format("{0}", reader[0])); + } + } + } + } + + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + + + An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + The current state of the connection is closed. requires an open . + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + One of the values. + + + Sends the to the , and builds a using one of the values. + + + A object. + + + + When the property is set to , the property should be set to the name of the stored procedure. The command executes this stored procedure when you call . + + + Use to retrieve large values and binary data. Otherwise, an might occur and the connection will be closed. + + + The multiple active result set (MARS) feature allows for multiple actions using the same connection. + + + If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. + + + + + The following example creates a , and then executes it by passing a string that is a Transact-SQL SELECT statement, and a string to use to connect to the data source. is set to . + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + 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); + connection.Open(); + SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection); + while (reader.Read()) + { + Console.WriteLine(String.Format("{0}", reader[0])); + } + } + } + } + + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + An asynchronous version of , which sends the to the and builds a . Exceptions will be reported via the returned Task object. + + + A task representing the asynchronous operation. + + + + For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see Asynchronous Programming. + + + For long-running queries on the server, consider using due to a known issue with canceling queries via a cancellation token. Also, consider canceling execution using the method. + + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + An invalid value. + + + + + Calling more than once for the same instance before task completion. + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + SQL Server returned an error while executing the command text. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + Options for statement execution and data retrieval. When is set to , reads the entire row before returning a complete Task. + + + An asynchronous version of , which sends the to the , and builds a . Exceptions will be reported via the returned Task object. + + + A task representing the asynchronous operation. + + + For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see Asynchronous Programming. + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + An invalid value. + + + + + Calling more than once for the same instance before task completion. + + + closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + SQL Server returned an error while executing the command text. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + The cancellation instruction. + + + An asynchronous version of , which sends the to the and builds a . The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. + + + A task representing the asynchronous operation. + + + For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see Asynchronous Programming. + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + An invalid value. + + + + + Calling more than once for the same instance before task completion. + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + SQL Server returned an error while executing the command text. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + Options for statement execution and data retrieval. When is set to , reads the entire row before returning a complete Task. + + + The cancellation instruction. + + + An asynchronous version of , which sends the to the , and builds a The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. + + + A task representing the asynchronous operation. + + + For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see Asynchronous Programming. + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + An invalid value. + + + + + Calling more than once for the same instance before task completion. + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + SQL Server returned an error while executing the command text. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. + + + The first column of the first row in the result set, or a null reference ( in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters. + + + + Use the method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the method, and then performing the operations that you need to generate the single value using the data returned by a . + + + + + A typical query can be formatted as in the following C# example: + + + cmd.CommandText = "SELECT COUNT(*) FROM dbo.region"; + Int32 count = (Int32) cmd.ExecuteScalar(); + + + + + The following example creates a and then executes it using . The example is passed a string representing a new value to be inserted into a table, and a string to use to connect to the data source. The function returns the new Identity column value if a new row was inserted, 0 on failure. > + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + public class Sample + { + public void CreateSqlCommand(string queryString, SqlConnection connection) + { + SqlCommand command = new SqlCommand(queryString, connection); + command.Connection.Open(); + command.ExecuteScalar(); + connection.Close(); + } + } + + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + + + An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + The cancellation instruction. + + + An asynchronous version of , which executes the query asynchronously and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. + + + A task representing the asynchronous operation. + + + + For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see Asynchronous Programming. + + + For long-running queries on the server, consider using due to a known issue with canceling queries via a cancellation token. Also, consider canceling execution using the method. + + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + + + Calling more than once for the same instance before task completion. + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + SQL Server returned an error while executing the command text. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + Sends the to the and builds an object. + + + An object. + + + + The returned by this method does not support asynchronous operations. The property ordinarily specifies a Transact-SQL statement with a valid FOR XML clause. However, can also specify a statement that returns ntext or nvarchar data that contains valid XML, or the contents of a column defined with the xml data type. + + + A typical query can be formatted as in the following Microsoft Visual C# example: + + + SqlCommand command = new SqlCommand("SELECT * FROM dbo.Customers FOR XML AUTO, XMLDATA", SqlConn); + + + This method can also be used to retrieve a single-row, single-column result set that contains XML data. In this case, if more than one row is returned, the method attaches the to the value on the first row, and discards the rest of the result set. + + + The multiple active result set (MARS) feature allows for multiple actions using the same connection. + + + If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. + + + + + The following example creates a and then executes it using . The example is passed a string that is a Transact-SQL FOR XML SELECT statement, and a string to use to connect to the data source. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + private static void CreateXMLReader(string queryString, string connectionString) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + SqlCommand command = new SqlCommand(queryString, connection); + System.Xml.XmlReader reader = command.ExecuteXmlReader(); + } + } + + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + + + An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + An asynchronous version of , which sends the to the and builds an object. + Exceptions will be reported via the returned Task object. + + + A task representing the asynchronous operation. + + + + The returned by this method does not support asynchronous operations. For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see Asynchronous Programming. + + + For long-running queries on the server, consider using due to a known issue with canceling queries via a cancellation token. Also, consider canceling execution using the method. + + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + + + Calling more than once for the same instance before task completion. + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + SQL Server returned an error while executing the command text. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + An error occurred in a , or object during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + The cancellation instruction. + + + An asynchronous version of , which sends the to the and builds an object. The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. + + + A task representing the asynchronous operation. + + + The returned by this method does not support asynchronous operations. For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see Asynchronous Programming. + + + + + A other than Binary or VarBinary was used when was set to . For more information about streaming, see SqlClient Streaming Support. + + + A other than Char, NChar, NVarChar, VarChar, or Xml was used when was set to . + + + A other than Xml was used when was set to . + + + + + + + Calling more than once for the same instance before task completion. + + + The closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + + + SQL Server returned an error while executing the command text. + + + A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + An error occurred in a , or object during a streaming operation.For more information about streaming, see SqlClient Streaming Support. + + + The , or object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support. + + + + + Gets or sets a value that specifies the object bound to this command. - A value indicating whether the command object should optimize parameter performance by disabling Output and InputOuput parameter directions when submitting the command to the SQL Server. - The default is . + When set to null (default), no notification should be requested. - - [!NOTE] -If the option is enabled and a parameter with Direction Output or InputOutput is present in the Parameters collection an InvalidOperationException will be thrown when the command is executed. - -]]> - + You must set the value for this property before the command is executed for it to take effect. - - - - The - - returned by the call to - - . - - - Finishes asynchronous execution of a Transact-SQL statement. - - - The number of rows affected (the same behavior as - - ). - - - to execute a Transact-SQL statement, you must call in order to complete the operation. If the process of executing the command has not yet finished, this method blocks until the operation is complete. Users can verify that the command has completed its operation by using the instance returned by the method. If a callback procedure was specified in the call to , this method must be called. - -## Examples -For examples demonstrating the use of the method, see . -]]> - - - - parameter is null ( - - in Microsoft Visual Basic) - - - - was called more than once for a single command execution, or the method was mismatched against its execution method (for example, the code called - - to complete execution of a call to - - . - - - The amount of time specified in - - elapsed and the asynchronous operation specified with - - is not complete. - - -or- - - In some situations, - - can be set to - - incorrectly. If this occurs and - - is called, EndExecuteNonQuery could raise a SqlException error if the amount of time specified in - - elapsed and the asynchronous operation specified with - - is not complete. To correct this situation, you should either increase the value of CommandTimeout or reduce the work being done by the asynchronous operation. - - - - - To be added. - - - To be added. - - - - - The - - returned by the call to - - . - - - Finishes asynchronous execution of a Transact-SQL statement, returning the requested - - . - - - A - - object that can be used to retrieve the requested rows. - - - to execute a Transact-SQL statement, you must call in order to complete the operation. If the process of executing the command has not yet finished, this method blocks until the operation is complete. Users can verify that the command has completed its operation by using the instance returned by the method. If a callback procedure was specified in the call to , this method must be called. - - -## Examples -For examples demonstrating the use of the method, see . -]]> - - - - parameter is null ( - - in Microsoft Visual Basic) - - - - was called more than once for a single command execution, or the method was mismatched against its execution method (for example, the code called - - to complete execution of a call to - - . - - - - - The - - returned by the call to - - . - - - Finishes asynchronous execution of a Transact-SQL statement, returning the requested data as XML. - - - An - - object that can be used to fetch the resulting XML data. - - - to execute a Transact-SQL statement, you must call in order to complete the operation. If the process of executing the command has not yet finished, this method blocks until the operation is complete. Users can verify that the command has completed its operation by using the instance returned by the method. If a callback procedure was specified in the call to , this method must be called. - -## Examples -For examples demonstrating the use of the method, see . -]]> - - - - parameter is null ( - - in Microsoft Visual Basic) - - - - was called more than once for a single command execution, or the method was mismatched against its execution method (for example, the code called - - to complete execution of a call to - - . - - - - - 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. - - - - - Executes a Transact-SQL statement against the connection and returns the number of rows affected. - - - The number of rows affected. - - - to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a by executing UPDATE, INSERT, or DELETE statements. - -Although the returns no rows, any output parameters or return values mapped to parameters are populated with data. - -For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1. -When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. -When SET NOCOUNT ON is set on the connection (before or as part of executing the command, or as part of a trigger initiated by the execution of the command) the rows affected by individual statements stop contributing to the count of rows affected that is returned by this method. -If no statements are detected that contribute to the count, the return value is -1. If a rollback occurs, the return value is also -1. -## Examples -The following example creates a and then executes it using . The example is passed a string that is a Transact-SQL statement (such as UPDATE, INSERT, or DELETE) and a string to use to connect to the data source. - -[!code-csharp[SqlCommand_ExecuteNonQuery](~/../sqlclient/doc/samples/SqlCommand_ExecuteNonQuery.cs)] -]]> - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - The cancellation instruction. - - - An asynchronous version of - - , which executes a Transact-SQL statement against the connection and returns the number of rows affected. The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. - - - A task representing the asynchronous operation. - - - [!NOTE] -> For long running queries on the server, consider using due to a known issue with canceling queries via a cancellation token. Also, consider canceling execution using the method. - - -]]> - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - Calling - - more than once for the same instance before task completion. - - -or- - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - SQL Server returned an error while executing the command text. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - Sends the - - to the - - and builds a - - . - - - A - - object. - - - property is set to `StoredProcedure`, the property should be set to the name of the stored procedure. The command executes this stored procedure when you call . - -> [!NOTE] -> If a transaction is deadlocked, an exception may not be thrown until is called. - -The multiple active result set (MARS) feature allows for multiple actions using the same connection. - -If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. - - -## Examples -The following example creates a , and then executes it by passing a string that is a Transact-SQL SELECT statement, and a string to use to connect to the data source. - -[!code-csharp[SqlCommand_ExecuteReader](~/../sqlclient/doc/samples/SqlCommand_ExecuteReader.cs)] -]]> - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The current state of the connection is closed. - - requires an open - - . - - -or- - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - One of the - - values. - - - Sends the - - to the - - , and builds a - - using one of the - - values. - - - A - - object. - - - property is set to `StoredProcedure`, the property should be set to the name of the stored procedure. The command executes this stored procedure when you call . - -> [!NOTE] -> Use to retrieve large values and binary data. Otherwise, an might occur and the connection will be closed. - -The multiple active result set (MARS) feature allows for multiple actions using the same connection. - -If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. - -## Examples -The following example creates a , and then executes it by passing a string that is a Transact-SQL SELECT statement, and a string to use to connect to the data source. is set to . - -[!code-csharp[SqlCommand_ExecuteReader2](~/../sqlclient/doc/samples/SqlCommand_ExecuteReader2.cs#1)] -]]> - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - An asynchronous version of - - , which sends the - - to the - - and builds a - - . Exceptions will be reported via the returned Task object. - - - A task representing the asynchronous operation. - - - [!NOTE] -> For long running queries on the server, consider using due to a known issue with canceling queries via a cancellation token. Also, consider canceling execution using the method. - -]]> - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - An invalid - - value. - - - Calling - - more than once for the same instance before task completion. - - -or- - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - SQL Server returned an error while executing the command text. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - Options for statement execution and data retrieval. When is set to - - , - - reads the entire row before returning a complete Task. - - - An asynchronous version of - - , which sends the - - to the - - , and builds a - - . Exceptions will be reported via the returned Task object. - - - A task representing the asynchronous operation. - - - - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - An invalid - - value. - - - Calling - - more than once for the same instance before task completion. - - -or- - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - SQL Server returned an error while executing the command text. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - The cancellation instruction. - - - An asynchronous version of - - , which sends the - - to the - - and builds a - - . - - The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. - - - A task representing the asynchronous operation. - - - - - - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - An invalid - - value. - - - Calling - - more than once for the same instance before task completion. - - -or- - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - SQL Server returned an error while executing the command text. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - Options for statement execution and data retrieval. When is set to - - , - - reads the entire row before returning a complete Task. - - - The cancellation instruction. - - - An asynchronous version of - - , which sends the - - to the - - , and builds a - - The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. - - - A task representing the asynchronous operation. - - - - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - An invalid - - value. - - - Calling - - more than once for the same instance before task completion. - - -or- - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - SQL Server returned an error while executing the command text. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. - - - The first column of the first row in the result set, or a null reference ( - - in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters. - - - method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the method, and then performing the operations that you need to generate the single value using the data returned by a . - -A typical query can be formatted as in the following C# example: - -```csharp -cmd.CommandText = "SELECT COUNT(*) FROM dbo.region"; -Int32 count = (Int32) cmd.ExecuteScalar(); -``` - -## Examples -The following example creates a and then executes it using . The example is passed a string representing a new value to be inserted into a table, and a string to use to connect to the data source. The function returns the new **Identity** column value if a new row was inserted, 0 on failure. - -[!code-csharp[SqlCommand.ExecuteScalar#1](~/../sqlclient/doc/samples/SqlCommand_ExecuteScalar.cs#1)] -]]> - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - The cancellation instruction. - - - An asynchronous version of - - , which executes the query asynchronously and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. - - The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. - - - A task representing the asynchronous operation. - - - [!NOTE] -> For long running queries on the server, consider using due to a known issue with canceling queries via a cancellation token. Also, consider canceling execution using the method. - -]]> - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - Calling - - more than once for the same instance before task completion. - - -or- - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - SQL Server returned an error while executing the command text. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - Sends the - - to the - - and builds an - - object. - - - An - - object. - - - property ordinarily specifies a Transact-SQL statement with a valid FOR XML clause. However, can also specify a statement that returns `ntext` or `nvarchar` data that contains valid XML, or the contents of a column defined with the `xml` data type. - -A typical query can be formatted as in the following Microsoft Visual C# example: - -```csharp -SqlCommand command = new SqlCommand("SELECT * FROM dbo.Customers FOR XML AUTO, XMLDATA", SqlConn); -``` - -This method can also be used to retrieve a single-row, single-column result set that contains XML data. In this case, if more than one row is returned, the method attaches the to the value on the first row, and discards the rest of the result set. - -The multiple active result set (MARS) feature allows for multiple actions using the same connection. - -If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries. - -## Examples -The following example creates a and then executes it using . The example is passed a string that is a Transact-SQL FOR XML SELECT statement, and a string to use to connect to the data source. - -[!code-csharp[SqlCommand_ExecuteXmlReader#1](~/../sqlclient/doc/samples/SqlCommand_ExecuteXmlReader.cs#1)] -]]> - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - An asynchronous version of - - , which sends the - - to the - - and builds an - - object. - - Exceptions will be reported via the returned Task object. - - - A task representing the asynchronous operation. - - - [!NOTE] -> For long running queries on the server, consider using due to a known issue with canceling queries via a cancellation token. Also, consider canceling execution using the method. - -]]> - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - Calling - - more than once for the same instance before task completion. - - -or- - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - SQL Server returned an error while executing the command text. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - The cancellation instruction. - - - An asynchronous version of - - , which sends the - - to the - - and builds an - - object. - - The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object. - - - A task representing the asynchronous operation. - - - - - - A - - other than **Binary** or **VarBinary** was used when - - was set to - - . For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - -or- - - A - - other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when - - was set to - - . - - -or- - - A - - other than **Xml** was used when - - was set to - - . - - - Calling - - more than once for the same instance before task completion. - - -or- - - The - - closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - SQL Server returned an error while executing the command text. - - -or- - - A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - An error occurred in a - - , - - or - - object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - The - - , - - or - - object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support). - - - - - Gets or sets a value that specifies the - - object bound to this command. - - - When set to null (default), no notification should be requested. - - - - - - - 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 or - 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. - - - - - - - - Gets or sets a value that specifies the - - object bound to this command. - - - When set to null (default), the default non-retriable provider will be used. - - - type. -2. Create a by using one of the following static methods of the class: - - - - - - - - -3. Assign the object to the `RetryLogicProvider` property. - -> [!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. - -> [!NOTE] -> The command **timeout** restarts for each execution of a command within the retry logic and after applying the retry time delay. There is no timing overlap between these two actions. - -> [!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 configuration file](/sql/connect/ado-net/configurable-retry-logic-config-file-sqlclient). - -> [!CAUTION] -> A command with isn't compatible with the built-in retry logic. The underlying connection is immediately closed after the first execution attempt and is no longer available for subsequent retries. - -## Example -The following sample creates a database and establishes an active connection to it. While the database has an active connection, it tries to drop it with a new and a that uses a . You should kill the active connection through the database to unblock the second command before exceeding the number of retries. -The blocking connection simulates a situation like a command still running in the database and unlikely to finish. - -[!code-csharp[SqlConfigurableRetryLogic_SqlCommand#1](~/../sqlclient/doc/samples/SqlConfigurableRetryLogic_SqlCommand.cs#1)] - -### How to use with synchronous commands - -[!code-csharp[SqlConfigurableRetryLogic_SqlCommand#2](~/../sqlclient/doc/samples/SqlConfigurableRetryLogic_SqlCommand.cs#2)] - -### How to use with asynchoronous commands - -[!code-csharp[SqlConfigurableRetryLogic_SqlCommand#3](~/../sqlclient/doc/samples/SqlConfigurableRetryLogic_SqlCommand.cs#3)] - -### How to use with legacy asynchronous commands -Besides assigning the provider to the command and executing the command, it's possible to run it directly using the following methods: -- -- -- - -[!code-csharp[SqlConfigurableRetryLogic_SqlCommand#4](~/../sqlclient/doc/samples/SqlConfigurableRetryLogic_SqlCommand.cs#4)] - -> [!NOTE] -> The Asynchronous Programming Model (APM) is a legacy pattern that uses a pair of methods starting with `Begin` and `End`, and an interface called `IAsyncResult`. It's not recommended to use this pattern in new applications. These methods are for backwards compatibility. - -]]> - - - - - Gets or sets a value indicating whether the application should automatically receive query notifications from a common - - object. - - - - if the application should automatically receive query notifications; otherwise - - . The default value is - - . - - - - - - - - Gets the - - . - - - The parameters of the Transact-SQL statement or stored procedure. The default is an empty collection. - - - [!NOTE] -> If the parameters in the collection do not match the requirements of the query to be executed, an error may result. - -For more information, see [Configuring parameters](/sql/connect/ado-net/configure-parameters). - -## Examples -The following example demonstrates how to create a and add parameters to the . - -[!code-csharp[SqlParameterCollection.AddWithValue#1](~/../sqlclient/doc/samples/SqlParameterCollection_AddWithValue.cs#1)] -]]> - - - - - Creates a prepared version of the command on an instance of SQL Server. - - - is set to `StoredProcedure`, the call to should succeed, although it may cause a no-op. - -Before you call , specify the data type of each parameter in the statement to be prepared. For each parameter that has a variable length data type, you must set the property to the maximum size needed. returns an error if these conditions are not met. - -> [!NOTE] -> If the database context is changed by executing the Transact-SQL `USE ` statement, or by calling the method, then must be called a second time. - -If you call an `Execute` method after calling , any parameter value that is larger than the value specified by the property is automatically truncated to the original specified size of the parameter, and no truncation errors are returned. - -Output parameters (whether prepared or not) must have a user-specified data type. If you specify a variable length data type, you must also specify the maximum . - -Prior to Visual Studio 2010, threw an exception. Beginning in Visual Studio 2010, this method does not throw an exception. - -## Examples -The following example demonstrates the use of the method. - -[!code-csharp[SqlCommand.Prepare#1](~/../sqlclient/doc/samples/SqlCommand_Prepare.cs#1)] -]]> - - - - Resets the property to its default value. - - - is 30 seconds. -]]> - - - - - Occurs when the execution of a Transact-SQL statement completes. - - - To be added. - - - - - Creates a new instance of a object. - - - A object. - - - To be added. - - - - - Gets or sets the - - within which the - - executes. - - - The - - . The default value is - - . - - - property if it is already set to a specific value, and the command is in the process of executing. If you set the transaction property to a object that is not connected to the same as the object, an exception is thrown the next time that you attempt to execute a statement. -]]> - - - - - Gets or sets how command results are applied to the when used by the **Update** method of the . - - - One of the values. - - - value is **Both** unless the command is automatically generated (as in the case of the ), in which case the default is **None**. - -For more information about using the **UpdatedRowSource** property, see [DataAdapter Parameters](/sql/connect/ado-net/dataadapter-parameters). -]]> - - -
+ + + + 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 or 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 used. + + + + You must set the value for this property before the command is executed for it to take effect. + + + To apply the retry logic, do the following steps before executing the command: + + + + 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 command timeout restarts for each execution of a command within the retry logic and after applying the retry time delay. 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 configuration file. + + + A command with isn't compatible with the built-in retry logic. The underlying connection is immediately closed after the first execution attempt and is no longer available for subsequent retries. + + + + + The following sample creates a database and establishes an active connection to it. While the database has an active connection, it tries to drop it with a new and a that uses a . You should kill the active connection through the database to unblock the second command before exceeding the number of retries. The blocking connection simulates a situation like a command still running in the database and unlikely to finish. + + + + /// 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. + + 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}"; + private const string CreateDatabaseFormat = "CREATE 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), + AuthorizedSqlCondition = null, + // error number 3702 : Cannot drop database "xxx" because it is currently in use. + TransientErrors = new int[] { 3702 } + }; + + // 2. Create a retry provider + var provider = SqlConfigurableRetryFactory.CreateExponentialRetryProvider(options); + + // define the retrying event to report 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 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 a general connection. + s_generalConnection.Open(); + + try + { + // Assume the database is creating and other services are going to connect to it. + RetryCommand(provider); + } + catch + { + s_generalConnection.Close(); + // exception is thrown if connecting to the database isn't successful. + throw; + } + s_generalConnection.Close(); + } + + private static void ExecuteCommand(SqlConnection cn, string command) + { + using var cmd = cn.CreateCommand(); + cmd.CommandText = command; + cmd.ExecuteNonQuery(); + } + + private static void FindActiveSessions(SqlConnection cnn, string dbName) + { + using var cmd = cnn.CreateCommand(); + cmd.CommandText = "DECLARE @query NVARCHAR(max) = '';" + Environment.NewLine + + $"SELECT @query = @query + 'KILL ' + CAST(spid as varchar(50)) + ';' FROM sys.sysprocesses WHERE dbid = DB_ID('{dbName}')" + Environment.NewLine + + "SELECT @query AS Active_sessions;"; + var reader = cmd.ExecuteReader(); + if (reader.Read()) + { + Console.ForegroundColor = ConsoleColor.Green; + Console.Write($">> Execute the '{reader.GetString(0)}' command in SQL Server to unblock the running task."); + Console.ResetColor(); + } + reader.Close(); + } + + + How to use with synchronous commands: + + + + private static void RetryCommand(SqlRetryLogicBaseProvider provider) + { + // Change this if you already have a database with the same name in your database. + string dbName = "RetryCommand_TestDatabase"; + + // Subscribe a new event on retry event and discover the active sessions on a database + EventHandler<SqlRetryingEventArgs> retryEvent = (object s, SqlRetryingEventArgs e) => + { + // Run just at first execution + if (e.RetryCount == 1) + { + FindActiveSessions(s_generalConnection, dbName); + Console.WriteLine($"Before exceeding {provider.RetryLogic.NumberOfTries} attempts."); + } + }; + + provider.Retrying += retryEvent; + + // Create a new database. + ExecuteCommand(s_generalConnection, string.Format(CreateDatabaseFormat, dbName)); + Console.WriteLine($"The '{dbName}' database is created."); + + // Open a connection to the newly created database to block it from being dropped. + using var blockingCnn = new SqlConnection(string.Format(CnnStringFormat, dbName)); + blockingCnn.Open(); + Console.WriteLine($"Established a connection to '{dbName}' to block it from being dropped."); + + Console.WriteLine($"Dropping `{dbName}`..."); + // Try to drop the new database. + RetryCommandSync(provider, dbName); + + Console.WriteLine("Command executed successfully."); + + provider.Retrying -= retryEvent; + } + + private static void RetryCommandSync(SqlRetryLogicBaseProvider provider, string dbName) + { + using var cmd = s_generalConnection.CreateCommand(); + cmd.CommandText = string.Format(DropDatabaseFormat, dbName); + // 3. Assign the `provider` to the command + cmd.RetryLogicProvider = provider; + Console.WriteLine("The first attempt, before getting into the retry logic."); + cmd.ExecuteNonQuery(); + } + + + How to use with asynchronous commands: + + + + private static void RetryCommand(SqlRetryLogicBaseProvider provider) + { + // Change this if you already have a database with the same name in your database. + string dbName = "RetryCommand_TestDatabase"; + + // Subscribe to the retry event and discover active sessions in a database + EventHandler<SqlRetryingEventArgs> retryEvent = (object s, SqlRetryingEventArgs e) => + { + // Run just at first execution + if (e.RetryCount == 1) + { + FindActiveSessions(s_generalConnection, dbName); + Console.WriteLine($"Before exceeding {provider.RetryLogic.NumberOfTries} attempts."); + } + }; + + provider.Retrying += retryEvent; + + // Create a new database. + ExecuteCommand(s_generalConnection, string.Format(CreateDatabaseFormat, dbName)); + Console.WriteLine($"The '{dbName}' database is created."); + + // Open a connection to the newly created database to block it from being dropped. + using var blockingCnn = new SqlConnection(string.Format(CnnStringFormat, dbName)); + blockingCnn.Open(); + Console.WriteLine($"Established a connection to '{dbName}' to block it from being dropped."); + + Console.WriteLine("Dropping the database..."); + // Try to drop the new database. + RetryCommandAsync(provider, dbName).Wait(); + + Console.WriteLine("Command executed successfully."); + + provider.Retrying -= retryEvent; + } + + private static async Task RetryCommandAsync(SqlRetryLogicBaseProvider provider, string dbName) + { + using var cmd = s_generalConnection.CreateCommand(); + cmd.CommandText = string.Format(DropDatabaseFormat, dbName); + // 3. Assign the `provider` to the command + cmd.RetryLogicProvider = provider; + Console.WriteLine("The first attempt, before getting into the retry logic."); + await cmd.ExecuteNonQueryAsync(); + } + + + How to use with legacy asynchronous commands: + + + Besides assigning the provider to the command and executing the command, it's possible to run it directly using the following methods: + + + + + + + + + + + + + + + private static void RetryCommand(SqlRetryLogicBaseProvider provider) + { + // Change this if you already have a database with the same name in your database. + string dbName = "RetryCommand_TestDatabase"; + + // Subscribe to the retry event and discover the active sessions in a database + EventHandler<SqlRetryingEventArgs> retryEvent = (object s, SqlRetryingEventArgs e) => + { + // Run just at first execution + if (e.RetryCount == 1) + { + FindActiveSessions(s_generalConnection, dbName); + Console.WriteLine($"Before exceeding {provider.RetryLogic.NumberOfTries} attempts."); + } + }; + + provider.Retrying += retryEvent; + + // Create a new database. + ExecuteCommand(s_generalConnection, string.Format(CreateDatabaseFormat, dbName)); + Console.WriteLine($"The '{dbName}' database is created."); + + // Open a connection to the newly created database to block it from being dropped. + using var blockingCnn = new SqlConnection(string.Format(CnnStringFormat, dbName)); + blockingCnn.Open(); + Console.WriteLine($"Established a connection to '{dbName}' to block it from being dropped."); + + Console.WriteLine("Dropping the database..."); + // Try to drop the new database. + RetryCommandBeginExecuteAsync(provider, dbName).Wait(); + + Console.WriteLine("Command executed successfully."); + + provider.Retrying -= retryEvent; + } + + private static async Task RetryCommandBeginExecuteAsync(SqlRetryLogicBaseProvider provider, string dbName) + { + using var cmd = s_generalConnection.CreateCommand(); + cmd.CommandText = string.Format(DropDatabaseFormat, dbName); + // Execute the BeginExecuteXXX and EndExecuteXXX functions by using Task.Factory.FromAsync(). + // Apply the retry logic by using the ExecuteAsync function of the configurable retry logic provider. + Console.WriteLine("The first attempt, before getting into the retry logic."); + await provider.ExecuteAsync(cmd, () => Task.Factory.FromAsync(cmd.BeginExecuteNonQuery(), cmd.EndExecuteNonQuery)); + } + + + + + + Gets or sets a value indicating whether the application should automatically receive query notifications from a common object. + + + if the application should automatically receive query notifications; otherwise . The default value is . + + + This feature is used in ASP.NET applications to receive notifications for all commands executed in an ASP page against SQL Server. This enables ASP.NET to cache the page until the queries used to render the page would produce a different result. Automatic enlistment. + + + This property applies only to versions of SQL Server that support query notifications. For earlier versions, setting this property to has no effect on the application. + + + + + + Gets the . + + + The parameters of the Transact-SQL statement or stored procedure. The default is an empty collection. + + + + The Microsoft .NET Framework Data Provider for SQL Server does not support the question mark (?) placeholder for passing parameters to a SQL Statement or a stored procedure called by a command of . In this case, named parameters must be used. For example: + + + SELECT * FROM Customers WHERE CustomerID = @CustomerID + + + If the parameters in the collection do not match the requirements of the query to be executed, an error may result. + + + For more information, see Configuring parameters. + + + + + The following example demonstrates how to create a and add parameters to the . + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + class Program + { + static void Main() + { + string connectionString = GetConnectionString(); + string demo = @"<StoreSurvey xmlns=""http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey""><AnnualSales>1500000</AnnualSales><AnnualRevenue>150000</AnnualRevenue><BankName>Primary International</BankName><BusinessType>OS</BusinessType><YearOpened>1974</YearOpened><Specialty>Road</Specialty><SquareFeet<38000</SquareFeet><Brands>3</Brands><Internet>DSL</Internet><NumberEmployees>40</NumberEmployees></StoreSurvey>"; + Int32 id = 3; + UpdateDemographics(id, demo, connectionString); + Console.ReadLine(); + } + private static void UpdateDemographics(Int32 customerID, + string demoXml, string connectionString) + { + // Update the demographics for a store, which is stored + // in an xml column. + string commandText = "UPDATE Sales.Store SET Demographics = @demographics " + + "WHERE CustomerID = @ID;"; + + using (SqlConnection connection = new SqlConnection(connectionString)) + { + SqlCommand command = new SqlCommand(commandText, connection); + command.Parameters.Add("@ID", SqlDbType.Int); + command.Parameters["@ID"].Value = customerID; + + // Use AddWithValue to assign Demographics. + // SQL Server will implicitly convert strings into XML. + command.Parameters.AddWithValue("@demographics", demoXml); + + try + { + connection.Open(); + Int32 rowsAffected = command.ExecuteNonQuery(); + Console.WriteLine("RowsAffected: {0}", rowsAffected); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + } + + static private string GetConnectionString() + { + // To avoid storing the connection string in your code, + // you can retrieve it from a configuration file. + return "Data Source=(local);Initial Catalog=AdventureWorks;" + + "Integrated Security=SSPI"; + } + } + + + + + + Creates a prepared version of the command on an instance of SQL Server. + + + + If is set to , the call to should succeed, although it may cause a no-op. + + + Before you call , specify the data type of each parameter in the statement to be prepared. For each parameter that has a variable length data type, you must set the property to the maximum size needed. returns an error if these conditions are not met. + + + If the database context is changed by executing the Transact-SQL USE <database> statement, or by calling the method, then must be called a second time. + + + If you call an Execute* method after calling , any parameter value that is larger than the value specified by the property is automatically truncated to the original specified size of the parameter, and no truncation errors are returned. + + + Output parameters (whether prepared or not) must have a user-specified data type. If you specify a variable length data type, you must also specify the maximum . + + + Prior to Visual Studio 2010, threw an exception. Beginning in Visual Studio 2010, this method does not throw an exception. + + + + + The following example demonstrates the use of the method. + + + + using System; + using System.Data; + using Microsoft.Data.SqlClient; + + namespace SqlPrepareCS + { + class Program + { + static void Main() + { + string connectionString = "Persist Security Info=False;Integrated Security=SSPI;database=Northwind;server=(local)"; + SqlCommandPrepareEx(connectionString); + Console.ReadLine(); + + } + private static void SqlCommandPrepareEx(string connectionString) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + SqlCommand command = new SqlCommand(null, connection); + + // Create and prepare an SQL statement. + command.CommandText = + "INSERT INTO Region (RegionID, RegionDescription) " + + "VALUES (@id, @desc)"; + SqlParameter idParam = new SqlParameter("@id", SqlDbType.Int, 0); + SqlParameter descParam = new SqlParameter("@desc", SqlDbType.Text, 100); + idParam.Value = 20; + descParam.Value = "First Region"; + command.Parameters.Add(idParam); + command.Parameters.Add(descParam); + + // Call Prepare after setting the Commandtext and Parameters. + command.Prepare(); + command.ExecuteNonQuery(); + + // Change parameter values and call ExecuteNonQuery. + command.Parameters[0].Value = 21; + command.Parameters[1].Value = "Second Region"; + command.ExecuteNonQuery(); + } + } + } + } + + + + + + Resets the property to its default value. + + + The default value of the is 30 seconds. + + + + + Occurs when the execution of a Transact-SQL statement completes. + + + + + Gets or sets the within which the executes. + + + The . The default value is . + + + You cannot set the property if it is already set to a specific value, and the command is in the process of executing. If you set the transaction property to a object that is not connected to the same as the object, an exception is thrown the next time that you attempt to execute a statement. + + + + + Gets or sets how command results are applied to the when used by the Update method of the . + + + One of the values. + + + + The default value is unless the command is automatically generated (as in the case of the ), in which case the default is . + + + For more information about using the UpdatedRowSource property, see DataAdapter Parameters. + + + +
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 9f789d36fd..75b9e2905a 100644 --- a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs +++ b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs @@ -687,15 +687,15 @@ public event System.Data.StatementCompletedEventHandler StatementCompleted { add public System.IAsyncResult BeginExecuteNonQuery(System.AsyncCallback callback, object stateObject) { throw null; } /// public System.IAsyncResult BeginExecuteReader() { throw null; } - /// + /// public System.IAsyncResult BeginExecuteReader(System.AsyncCallback callback, object stateObject) { throw null; } - /// + /// public System.IAsyncResult BeginExecuteReader(System.AsyncCallback callback, object stateObject, System.Data.CommandBehavior behavior) { throw null; } /// public System.IAsyncResult BeginExecuteReader(System.Data.CommandBehavior behavior) { throw null; } /// public System.IAsyncResult BeginExecuteXmlReader() { throw null; } - /// + /// public System.IAsyncResult BeginExecuteXmlReader(System.AsyncCallback callback, object stateObject) { throw null; } /// public override void Cancel() { } @@ -708,7 +708,7 @@ public override void Cancel() { } public new Microsoft.Data.SqlClient.SqlParameter CreateParameter() { throw null; } /// public int EndExecuteNonQuery(System.IAsyncResult asyncResult) { throw null; } - /// + /// public Microsoft.Data.SqlClient.SqlDataReader EndExecuteReader(System.IAsyncResult asyncResult) { throw null; } /// public System.Xml.XmlReader EndExecuteXmlReader(System.IAsyncResult asyncResult) { throw null; } 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 d8bbb83106..2a581480d5 100644 --- a/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs +++ b/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs @@ -449,7 +449,7 @@ public sealed partial class SqlClientPermission : System.Data.Common.DBDataPermi public SqlClientPermission() : base(default(System.Security.Permissions.PermissionState)) { } /// public SqlClientPermission(System.Security.Permissions.PermissionState state) : base(default(System.Security.Permissions.PermissionState)) { } - /// + /// [System.ObsoleteAttribute("SqlClientPermission(PermissionState state, Boolean allowBlankPassword) has been deprecated. Use the SqlClientPermission(PermissionState.None) constructor. http://go.microsoft.com/fwlink/?linkid=14202", true)] public SqlClientPermission(System.Security.Permissions.PermissionState state, bool allowBlankPassword) : base(default(System.Security.Permissions.PermissionState)) { } ///