2013-08-25 113 views
0

今天的另一個問題。這一次,我無法從SQL Server CE數據庫中刪除一行。需要從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命令之前,將關閉。

回答

2

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