需要有关从SQL Server CE数据库中删除行的帮助

时间:2013-08-25 04:08:39

标签: c# database sql-server-ce delete-row

今天的另一个问题。这次,我在从SQL Server CE数据库中删除一行时遇到了麻烦。

private void Form1_Load(object sender, EventArgs e)
{
        // Create a connection to the file datafile.sdf in the program folder
        string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\userDtbs.sdf";
        SqlCeConnection connection = new SqlCeConnection("datasource=" + dbfile);

        // Read all rows from the table test_table into a dataset (note, the adapter automatically opens the connection)
        SqlCeDataAdapter adapter = new SqlCeDataAdapter("SELECT * FROM history", connection);
        DataSet data = new DataSet();
        adapter.Fill(data);

        //Delete from the database
        using (SqlCeCommand com = new SqlCeCommand("DELETE FROM accounts WHERE Id = 0", connection))
        {
            com.ExecuteNonQuery();
        }

        // Save data back to the databasefile
        var cmd = new SqlCeCommandBuilder(adapter);
        adapter.Update(data);

        // Close 
        connection.Close();
}

我的程序给了我一个错误,告诉我connection处于关闭状态,我无法弄清楚为什么它会在执行DELETE命令之前关闭。

1 个答案:

答案 0 :(得分:2)

请注意:执行Command.ExecuteXXX()命令要求首先打开连接。使用DataSet将数据填充到SqlDataAdapter.Fill并不需要,因为它在内部处理。以这种方式执行SQL query是直接的,不需要Update上的任何adapter方法调用(在删除后添加代码时)。 Update仅用于保存对DataSet所做的更改。

    //Delete from the database
    using (SqlCeCommand com = new SqlCeCommand("DELETE FROM accounts WHERE Id = 0", connection))
    {
        if(connection.State == ConnectionState.Closed) connection.Open();
        com.ExecuteNonQuery();
    }