如何删除断开连接的架构中的数据?

时间:2015-10-21 08:58:33

标签: ado.net

如何使用查询删除断开连接的架构中的数据。 我试过但没有任何反应。

OleDbConnection connection = new OleDbConnection();
        OleDbCommand command = new OleDbCommand();
        OleDbDataAdapter adapter = new OleDbDataAdapter();
        OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
        DataSet dataset = new DataSet();

        connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Vova\\Desktop\\fenix.accdb";
        command.Connection = connection;
        command.CommandText = "SELECT * FROM ZZZ";
        adapter.SelectCommand = command;
        adapter.Fill(dataset, "ZZZ");

        string del = "delete from ZZZ where m_id=253";


        OleDbCommand delete = new OleDbCommand(del, command.Connection);



        adapter.DeleteCommand = delete;

        adapter.Update(dataset, "ZZZ");

更新后没有任何反应,仍记录在数据库中。

1 个答案:

答案 0 :(得分:0)

DataRow中您必须Delete DataTable,当您致电DeleteCommand时,此行会触发adapter.Update(dataset, "ZZZ");

例如:

DataRow rowToDelete = dataset.Tables["ZZZ"].AsEnumerable()
    .FirstOrDefault(row => row.Field<int>("m_id") == 253);
if(rowToDelete != null)
    rowToDelete.Delete();
adapter.Update(dataset, "ZZZ");

每次更改/删除操作后,您都无需致电Update。您可以在最后调用它,然后为每个更改的行触发相应的命令。

Enumerable.FirstOrDefault是LINQ方法,因此您需要添加using System.Linq;

如果您不想使用DataAdapterDataRow.Delete,那么您只能使用OleDbCommand实现相同目标:

using(var connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Vova\\Desktop\\fenix.accdb"))
using(var delete = new OleDbCommand("delete from ZZZ where m_id=253", connection ))
{
    connection.Open();
    int deleted = delete.ExecuteNonQuery();
}