1

I use OleDbCommand to run the sqlcommand that can update the Access database. But when I try to use OleDbDataAdapter and DataTable to update the database, it doesn't work.

using (OleDbConnection conn = new OleDbConnection(connStr))
        {
            conn.Open();
            OleDbDataAdapter adapter = new OleDbDataAdapter("select * from confirm", conn);
            OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
            DataTable table = new DataTable();
            adapter.Fill(table);
            DataRow row = table.NewRow();
            row["k"] = "november";
            row["v"] = "eleven";
           // table.AcceptChanges();
            adapter.UpdateCommand = builder.GetUpdateCommand();
            adapter.Update(table);
           // table.AcceptChanges();
            return table;
        }

When I run the code, the database doesn't change.

4

1 回答 1

0

DataRow row = table.NewRow();会创建一个带有表 shema 的行,但不会将该行添加到DataTable. 您需要将该行添加到表中:

table.Rows.Add(row);

完整代码

using (OleDbConnection conn = new OleDbConnection(connStr)) 
{
    conn.Open();
    OleDbDataAdapter adapter = new OleDbDataAdapter("select * from confirm", conn);
    OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
    DataTable table = new DataTable();
    adapter.Fill(table);
    DataRow row = table.NewRow();
    row("k") = "november";
    row("v") = "eleven";

    //**You missed this**
    table.Rows.Add(row);

    adapter.UpdateCommand = builder.GetUpdateCommand();
    adapter.Update(table);
    // table.AcceptChanges();
    return table;
}
于 2013-09-07T16:34:10.623 回答