手工写DataAdapter的UpdateCommend、InsertCommand和DeleteCommand

有时候需要手工的定义一个DataAdapter的UpdateCommend、InsertCommand和DeleteCommand,比如将数据库中的一个View绑定到了DataGridView的DataSource,但需要Update、Insert或Delete View中某个表的记录的情况。以下是一个OledbDataAdapter的例子:
public static OleDbDataAdapter CreateDataAdapter( string selectCommand,
        OleDbConnection connection)
{
        OleDbDataAdapter adapter = new OleDbDataAdapter(selectCommand, connection);

        adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

         // Create the Insert, Update and Delete commands.
        adapter.InsertCommand = new OleDbCommand(
                 "INSERT INTO Customers (CustomerID, CompanyName) " +
                 "VALUES (?, ?)");

        adapter.UpdateCommand = new OleDbCommand(
                 "UPDATE Customers SET CustomerID = ?, CompanyName = ? " +
                 "WHERE CustomerID = ?");

        adapter.DeleteCommand = new OleDbCommand(
                 "DELETE FROM Customers WHERE CustomerID = ?");

         // Create the parameters.
        adapter.InsertCommand.Parameters.Add( "@CustomerID",
                OleDbType.Char, 5, "CustomerID");
        adapter.InsertCommand.Parameters.Add( "@CompanyName",
                OleDbType.VarChar, 40, "CompanyName");

        adapter.UpdateCommand.Parameters.Add( "@CustomerID",
                OleDbType.Char, 5, "CustomerID");
        adapter.UpdateCommand.Parameters.Add( "@CompanyName",
                OleDbType.VarChar, 40, "CompanyName");
        adapter.UpdateCommand.Parameters.Add( "@oldCustomerID",
                OleDbType.Char, 5, "CustomerID").SourceVersion =
                DataRowVersion.Original;

        adapter.DeleteCommand.Parameters.Add( "@CustomerID",
                OleDbType.Char, 5, "CustomerID").SourceVersion =
                DataRowVersion.Original;

         return adapter;
}
这里用到的OleDbCommand.Parameters.Add()的定义为:
     参数名称、数据类型、列长和源列名称
Add(String, OleDbType, Int32, String)

你可能感兴趣的:(.net,职场,休闲,ADO.NET)