簡體   English   中英

需要有關從SQL Server CE數據庫中刪除行的幫助

[英]Need help on deleting row(s) 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();
}

我的程序給了我一個錯誤,告訴我connection處於關閉狀態,我無法弄清楚為什么它會在DELETE命令執行之前關閉。

請注意:使用Command.ExecuteXXX()執行命令需要首先打開連接。 使用SqlDataAdapter.Fill數據填充到DataSet中不需要,因為它在內部處理它。 以這種方式執行SQL query是直接的,並且不需要在adapter調用任何Update方法(因為您在刪除后添加了代碼)。 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