# 使用 CommandBuilder 生成命令Generating Commands with CommandBuilders

SelectCommand 还必须至少返回一个主键或唯一列。The SelectCommand must also return at least one primary key or unique column. 如果不存在任何主键和唯一列，则会生成 InvalidOperation 异常，并且不会生成命令。If none are present, an InvalidOperation exception is generated, and the commands are not generated.

## 自动生成命令的规则Rules for Automatically Generated Commands

CommandCommand 规则Rule
InsertCommand 在数据源处为表中所有 RowStateAdded 的行插入一行。Inserts a row at the data source for all rows in the table with a RowState of Added. 插入所有可更新列的值（但是不包括标识、表达式或时间戳等列）。Inserts values for all columns that are updateable (but not columns such as identities, expressions, or timestamps).
UpdateCommand 在数据源处更新表中所有 RowStateModified 的行。Updates rows at the data source for all rows in the table with a RowState of Modified. 更新所有列的值，不可更新的列除外，例如标识列或表达式列。Updates the values of all columns except for columns that are not updateable, such as identities or expressions. 更新符合以下条件的所有行：数据源中的列值匹配行的主键列值，并且数据源中的剩余列匹配行的原始值。Updates all rows where the column values at the data source match the primary key column values of the row, and where the remaining columns at the data source match the original values of the row. 有关更多信息，请参见本主题后面的“更新和删除的开放式并发模型”。For more information, see "Optimistic Concurrency Model for Updates and Deletes," later in this topic.
DeleteCommand 在数据源处删除表中所有 RowStateDeleted 的行。Deletes rows at the data source for all rows in the table with a RowState of Deleted. 删除符合以下条件的所有行：列值匹配行的主键列值，并且数据源中的剩余列匹配行的原始值。Deletes all rows where the column values match the primary key column values of the row, and where the remaining columns at the data source match the original values of the row. 有关更多信息，请参见本主题后面的“更新和删除的开放式并发模型”。For more information, see "Optimistic Concurrency Model for Updates and Deletes," later in this topic.

## 使用 CommandBuilder 自动生成 SQL 语句Using the CommandBuilder to Automatically Generate an SQL Statement

' Assumes that connection is a valid SqlConnection object
' inside of a Using block.
"SELECT * FROM dbo.Customers", connection)
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(adapter)
builder.QuotePrefix = "["
builder.QuoteSuffix = "]"

// Assumes that connection is a valid SqlConnection object
// inside of a using block.
"SELECT * FROM dbo.Customers", connection);
builder.QuotePrefix = "[";
builder.QuoteSuffix = "]";


## 修改 SelectCommandModifying the SelectCommand

Console.WriteLine(builder.GetUpdateCommand().CommandText)

Console.WriteLine(builder.GetUpdateCommand().CommandText);


' Assumes an open SqlConnection and SqlDataAdapter inside of a Using block.
"SELECT CustomerID, ContactName FROM dbo.Customers"
builder.RefreshSchema()

custDS.Tables.Remove(custDS.Tables("Customers"))

// Assumes an open SqlConnection and SqlDataAdapter inside of a using block.