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

一曲冷凌霜 提交于 2019-12-25 11:15:31

问题


Another question today. This time, I'm having trouble deleting a row from a SQL Server CE database.

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.


回答1:


Note that: executing command with Command.ExecuteXXX() requires the connection to be open first. Filling data into DataSet using SqlDataAdapter.Fill doesn't require that because it handles that internally. 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). Update is just for saving changes made on your 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();
    }


来源:https://stackoverflow.com/questions/18425612/need-help-on-deleting-rows-from-a-sql-server-ce-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!