【问题标题】:Need help on deleting row(s) from a SQL Server CE database从 SQL Server CE 数据库中删除行需要帮助)
【发布时间】:2013-08-25 15:08:53
【问题描述】:

今天还有一个问题。这一次,我无法从 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 命令之前关闭。

【问题讨论】:

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


    【解决方案1】:

    注意:使用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();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-23
      • 2017-09-28
      • 1970-01-01
      • 1970-01-01
      • 2010-11-11
      • 1970-01-01
      • 2015-10-10
      • 1970-01-01
      相关资源
      最近更新 更多