2 out of 6 rated this helpful - Rate this topic

SqlCommandBuilder Class

Automatically generates single-table commands that are used to reconcile changes made to a DataSet with the associated SQL Server database. This class cannot be inherited.

System.Object
  System.MarshalByRefObject
    System.ComponentModel.Component
      System.Data.Common.DbCommandBuilder
        System.Data.SqlClient.SqlCommandBuilder

Namespace:  System.Data.SqlClient
Assembly:  System.Data (in System.Data.dll)
public sealed class SqlCommandBuilder : DbCommandBuilder

The SqlCommandBuilder type exposes the following members.

  Name Description
Public method SqlCommandBuilder() Initializes a new instance of the SqlCommandBuilder class.
Public method SqlCommandBuilder(SqlDataAdapter) Initializes a new instance of the SqlCommandBuilder class with the associated SqlDataAdapter object.
Top
  Name Description
Protected property CanRaiseEvents Gets a value indicating whether the component can raise an event. (Inherited from Component.)
Public property CatalogLocation Sets or gets the CatalogLocation for an instance of the SqlCommandBuilder class. (Overrides DbCommandBuilder.CatalogLocation.)
Public property CatalogSeparator Sets or gets a string used as the catalog separator for an instance of the SqlCommandBuilder class. (Overrides DbCommandBuilder.CatalogSeparator.)
Public property ConflictOption Specifies which ConflictOption is to be used by the DbCommandBuilder. (Inherited from DbCommandBuilder.)
Public property Container Gets the IContainer that contains the Component. (Inherited from Component.)
Public property DataAdapter Gets or sets a SqlDataAdapter object for which Transact-SQL statements are automatically generated.
Protected property DesignMode Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Protected property Events Gets the list of event handlers that are attached to this Component. (Inherited from Component.)
Public property QuotePrefix Gets or sets the starting character or characters to use when specifying SQL Server database objects, such as tables or columns, whose names contain characters such as spaces or reserved tokens. (Overrides DbCommandBuilder.QuotePrefix.)
Public property QuoteSuffix Gets or sets the ending character or characters to use when specifying SQL Server database objects, such as tables or columns, whose names contain characters such as spaces or reserved tokens. (Overrides DbCommandBuilder.QuoteSuffix.)
Public property SchemaSeparator Gets or sets the character to be used for the separator between the schema identifier and any other identifiers. (Overrides DbCommandBuilder.SchemaSeparator.)
Public property SetAllValues Specifies whether all column values in an update statement are included or only changed ones. (Inherited from DbCommandBuilder.)
Public property Site Gets or sets the ISite of the Component. (Inherited from Component.)
Top
  Name Description
Protected method ApplyParameterInfo Allows the provider implementation of the DbCommandBuilder class to handle additional parameter properties. (Inherited from DbCommandBuilder.)
Public method CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public method Static member DeriveParameters Retrieves parameter information from the stored procedure specified in the SqlCommand and populates the Parameters collection of the specified SqlCommand object.
Public method Dispose() Releases all resources used by the Component. (Inherited from Component.)
Protected method Dispose(Boolean) Releases the unmanaged resources used by the DbCommandBuilder and optionally releases the managed resources. (Inherited from DbCommandBuilder.)
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Finalize Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Public method GetDeleteCommand() Gets the automatically generated SqlCommand object required to perform deletions on the database.
Public method GetDeleteCommand(Boolean) Gets the automatically generated SqlCommand object that is required to perform deletions on the database.
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetInsertCommand() Gets the automatically generated SqlCommand object required to perform insertions on the database.
Public method GetInsertCommand(Boolean) Gets the automatically generated SqlCommand object that is required to perform insertions on the database.
Public method GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method GetParameterName(Int32) Returns the name of the specified parameter in the format of @p#. Use when building a custom command builder. (Inherited from DbCommandBuilder.)
Protected method GetParameterName(String) Infrastructure. Returns the full parameter name, given the partial parameter name. (Inherited from DbCommandBuilder.)
Protected method GetParameterPlaceholder Infrastructure. Returns the placeholder for the parameter in the associated SQL statement. (Inherited from DbCommandBuilder.)
Protected method GetSchemaTable Returns the schema table for the DbCommandBuilder. (Inherited from DbCommandBuilder.)
Protected method GetService Returns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public method GetUpdateCommand() Gets the automatically generated SqlCommand object required to perform updates on the database.
Public method GetUpdateCommand(Boolean) Gets the automatically generated SqlCommand object required to perform updates on the database.
Protected method InitializeCommand Resets the CommandTimeout, Transaction, CommandType, and UpdateRowSource properties on the DbCommand. (Inherited from DbCommandBuilder.)
Public method InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method MemberwiseClone() Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method MemberwiseClone(Boolean) Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Public method QuoteIdentifier Given an unquoted identifier in the correct catalog case, returns the correct quoted form of that identifier. This includes correctly escaping any embedded quotes in the identifier. (Overrides DbCommandBuilder.QuoteIdentifier(String).)
Public method RefreshSchema Clears the commands associated with this DbCommandBuilder. (Inherited from DbCommandBuilder.)
Protected method RowUpdatingHandler Adds an event handler for the RowUpdating event. (Inherited from DbCommandBuilder.)
Protected method SetRowUpdatingHandler Registers the DbCommandBuilder to handle the RowUpdating event for a DbDataAdapter. (Inherited from DbCommandBuilder.)
Public method ToString Returns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.)
Public method UnquoteIdentifier Given a quoted identifier, returns the correct unquoted form of that identifier. This includes correctly unescaping any embedded quotes in the identifier. (Overrides DbCommandBuilder.UnquoteIdentifier(String).)
Top
  Name Description
Public event Disposed Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Top

The SqlDataAdapter does not automatically generate the Transact-SQL statements required to reconcile changes made to a DataSet with the associated instance of SQL Server. However, you can create a SqlCommandBuilder object to automatically generate Transact-SQL statements for single-table updates if you set the SelectCommand property of the SqlDataAdapter. Then, any additional Transact-SQL statements that you do not set are generated by the SqlCommandBuilder.

The SqlCommandBuilder registers itself as a listener for RowUpdating events whenever you set the DataAdapter property. You can only associate one SqlDataAdapter or SqlCommandBuilder object with each other at one time.

To generate INSERT, UPDATE, or DELETE statements, the SqlCommandBuilder uses the SelectCommand property to retrieve a required set of metadata automatically. If you change the SelectCommand after the metadata has been retrieved, such as after the first update, you should call the RefreshSchema method to update the metadata.

The SelectCommand must also return at least one primary key or unique column. If none are present, an InvalidOperation exception is generated, and the commands are not generated.

The SqlCommandBuilder also uses the Connection, CommandTimeout, and Transaction properties referenced by the SelectCommand. The user should call RefreshSchema if one or more of these properties are modified, or if the SelectCommand itself is replaced. Otherwise the InsertCommand, UpdateCommand, and DeleteCommand properties retain their previous values.

If you call Dispose, the SqlCommandBuilder is disassociated from the SqlDataAdapter, and the generated commands are no longer used.

The following example uses the SqlCommand, along SqlDataAdapter and SqlConnection, to select rows from a data source. The example is passed a connection string, a query string that is a Transact-SQL SELECT statement, and a string that is the name of the database table. The example then creates a SqlCommandBuilder.


public static DataSet SelectSqlRows(string connectionString,
    string queryString, string tableName)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = new SqlCommand(queryString, connection);
        SqlCommandBuilder builder = new SqlCommandBuilder(adapter);

        connection.Open();

        DataSet dataSet = new DataSet();
        adapter.Fill(dataSet, tableName);

        //code to modify data in DataSet here

        builder.GetUpdateCommand();

        //Without the SqlCommandBuilder this line would fail
        adapter.Update(dataSet, tableName);

        return dataSet;
    }
}


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Poor code
The example code is poorly written. First, the call to connection.Open() is unnecessary - this is called automatically during the Fill() method.
Second, the builder.UpdateCommand(); is useless - it returns a value which is never captured. (The code makes it look like it has some side-effect that necessitates a call to it for Update() to work.) That line of code should be removed.
Add vs AddWithValue

This may not be directly related to this class; though I discovered an interesting nuance while trying to use it. I'm populating a using a SELECT command and a prepared SqlCommand object, then using a SqlDataAdapter and SqlCommandBuilder to dynamically build the INSERT and UPDATEs. At first I was defining the parameters explicitly; then assigning the value. For example.

command.Parameters.Add("@myParam1", SqlDbType.VarChar, 10);

command.Prepare();

command.Parameters["@myParam1"].Value = "MyValue";

The SqlCommandBuilder was unable to dynamically build the INSERT and UPDATE statements. Or more specifically it complained there was no table meta information in the DataTable for it to do so. The table I'm using has primary keys, so as far as I was concearned it should work. After several hours of floundering I thought it might have something to do with the prepared command so I tried;

command.Parameters.AddWithValue("@myParam1", "MyValue");

And to my amazement this worked. The only "rule" I found in the documentation as far as the SelectCommand was;

"To generate INSERT, UPDATE, or DELETE statements, the SqlCommandBuilder uses the SelectCommand property to retrieve a required set of metadata automatically. If you change the SelectCommand after the metadata has been retrieved, such as after the first update, you should call the RefreshSchema method to update the metadata.

The SelectCommand must also return at least one primary key or unique column. If none are present, an InvalidOperation exception is generated, and the commands are not generated."

Although I was never explicitly defining it as a parameter; the table does contain a "text" field which is possibly part of the problem. Though if this is the case I would think there should be something in the documentation regarding this; and seems odd that it works fine when the parameters are defined with AddWithValue.

Bill

Unnecessary line in code?
The line
builder.GetUpdateCommand();
doesn't seem to do anything. The code works the same when it is removed.

Reply:
That's because GetUpdateCommand() is used to return the update command that a SqlCommandBuilder object automatically generates. It doesn't do anything to the DataAdapter or DataBuilder, it just returns a value.
You could store the returned value in a variable for further use. Here's an example:

SqlCommand cmd = builder.GetUpdateCommand();
Console.WriteLine(cmd.CommandText);//will display the automatically generated update command