在我的 C# 应用程序中,我正在与 SQL Compact 数据库进行交互。在这种情况下,我有三个表;customer
, list
, and 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 函数中,我传入了一个名为“close”的布尔参数。我添加了这个,因为在阅读器内部关闭与数据库的连接会导致上述错误。所以现在,如果我想在阅读器中使用这个函数,我调用 deleteList 函数并确保 'close' 参数作为false
. 这不是问题 - 这意味着在此函数中未调用 DbConnection.closeConnection。
所以我没有关闭阅读器,也没有关闭数据库连接。那么有什么想法为什么我仍然会收到这个错误?