简体   繁体   English

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

[英]Need help on deleting row(s) from a SQL Server CE database

Another question today. 今天另一个问题。 This time, I'm having trouble deleting a row from a SQL Server CE database. 这次,我在从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();
}

My program's giving me an error telling me that connection is in a closed state, and I can't figure out why it would close before the DELETE command is executed. 我的程序给了我一个错误,告诉我connection处于关闭状态,我无法弄清楚为什么它会在DELETE命令执行之前关闭。

Note that: executing command with Command.ExecuteXXX() requires the connection to be open first. 请注意:使用Command.ExecuteXXX()执行命令需要首先打开连接。 Filling data into DataSet using SqlDataAdapter.Fill doesn't require that because it handles that internally. 使用SqlDataAdapter.Fill数据填充到DataSet中不需要,因为它在内部处理它。 Executing the SQL query this way is direct and don't require any Update method call on adapter (as you add in your code after deleting). 以这种方式执行SQL query是直接的,并且不需要在adapter调用任何Update方法(因为您在删除后添加了代码)。 Update is just for saving changes made on your DataSet . 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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM