C# 需要有关从SQL Server CE数据库中删除行的帮助吗
今天还有一个问题。这一次,我在从SQLServerCE数据库中删除一行时遇到问题C# 需要有关从SQL Server CE数据库中删除行的帮助吗,c#,database,sql-server-ce,delete-row,C#,Database,Sql Server Ce,Delete Row,今天还有一个问题。这一次,我在从SQLServerCE数据库中删除一行时遇到问题 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.Get
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();
}
我的程序给我一个错误,告诉我
连接处于关闭状态,我不明白为什么它会在执行删除命令之前关闭。注意:使用命令执行命令。executexx()
需要先打开连接。使用SqlDataAdapter.Fill
将数据填充到DataSet
中不需要这样做,因为它在内部处理数据。以这种方式执行SQL查询
是直接的,并且不需要对适配器
进行任何更新
方法调用(当您在删除后添加代码时)<代码>更新
仅用于保存对数据集所做的更改
//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();
}