在我的C#應用程序中,我正在與SQL Compact數據庫進行交互。在這方面,我有三張桌子; customer
,list
和customerlist
(客戶和列表是多對多的關係)。閱讀器關閉時嘗試讀取無效 - 但不關閉閱讀器?
我有一個函數,當我想要刪除一個列表時調用。該功能也會刪除customerlist
表中的相關條目,只是爲了清潔(因爲如果列表本身已被刪除,它們將不復存在)。
我的代碼是這樣的:
private void clearRedundantSubscriptions()
{
string sql;
// Check if there are any entries in customerlist table which point to non-existing lists
try
{
sql = "select distinct cl.listid from customerlist cl inner join list l on cl.listid != l.listid";
SqlCeCommand cmdGetDisusedLists = new SqlCeCommand(sql, DbConnection.ceConnection);
SqlCeDataReader reader = cmdGetDisusedLists.ExecuteReader();
while (reader.Read())
{
DbFunctions.DeleteList(reader.GetInt32(0), false, false);
}
}
catch (Exception ex)
{
MessageBox.Show("Error cleaning up list entries." + ex.Message);
}
return;
}
public static bool DeleteList(int id, bool display, bool close)
{
string sql;
string title = "";
bool ranOk = false;
try
{
sql = "select ShortDesc from list where listid=" + id;
DbFunctions.runSQL(sql, out title);
sql = "delete from list where ListId=" + id;
SqlCeCommand cmdDelList = new SqlCeCommand(sql, DbConnection.ceConnection);
cmdDelList.ExecuteNonQuery();
sql = "delete from customerlist where listid=" + id;
SqlCeCommand cmdDelEntries = new SqlCeCommand(sql, DbConnection.ceConnection);
cmdDelEntries.ExecuteNonQuery();
if (display)
General.doneWork(title + " list deleted.");
ranOk = true;
}
catch (Exception ex)
{
if (display)
MessageBox.Show("Unable to delete list. " + ex.Message);
}
finally
{
if (close)
DbConnection.closeConnection();
}
return ranOk;
}
public static void closeConnection()
{
if (_sqlCeConnection != null)
_sqlCeConnection.Close();
}
你會在我deletelist功能注意到,我通過一個名爲「關閉」一個布爾參數。我添加了這個,因爲在閱讀器內關閉與數據庫的連接導致了上述錯誤。所以,現在,如果我想在閱讀器中使用這個函數,我調用deleteList函數並確保'close'參數被傳入爲false
。這不是問題 - 這意味着DbConnection.closeConnection是不是在此函數中調用。
所以我沒有關閉閱讀器,也沒有數據庫連接。那麼,爲什麼我仍然得到這個錯誤的任何想法?
您忘記了添加最重要的信息:_Where_你會得到異常嗎? – 2013-03-22 11:15:08
第二遍讀者:( – 2013-03-22 11:16:30
)您正在重新使用其他sql命令的相同連接,首先閱讀列表,然後使用DeleList()。 – 2013-03-22 11:17:58