我似乎在关闭数据库连接(Program.DB_CONNECTION)时出现问题。
当我关闭表单时,我运行Program.DB_CONNECTION.Close,但是这个dosnt似乎关闭了连接,因为数据库锁文件仍然存在,我无法删除数据库。
任何人都可以看到我做错了数据库不能关闭吗?
private void update_gic_attendances()
{
OleDbCommand com = new OleDbCommand("SELECT count(*), [Squadron] FROM Personnel WHERE [Position] = ? and [Current?] = TRUE GROUP BY [Squadron]", Program.DB_CONNECTION);
com.Parameters.Add(new OleDbParameter("", PositionIDs.GIC));
OleDbDataReader dr = com.ExecuteReader();
while (dr.Read())
{
try
{
OleDbCommand com2 = new OleDbCommand("SELECT * FROM GIC_Attendances WHERE [Attendance_Date] = ? AND [Squadron] = ?", Program.DB_CONNECTION);
com2.Parameters.Add(new OleDbParameter("", DateTime.Today.Date));
com2.Parameters.Add(new OleDbParameter("", dr.GetInt32(1)));
OleDbDataReader dr2 = com2.ExecuteReader();
if (dr2.HasRows)
{
//update the number of attendees
OleDbCommand com3 = new OleDbCommand("UPDATE GIC_Attendances SET [Number_Attended] = ? WHERE [Attendance_Date] = ? AND [Squadron] = ?", Program.DB_CONNECTION);
com3.Parameters.Add(new OleDbParameter("", dr.GetInt32(0)));
com3.Parameters.Add(new OleDbParameter("", DateTime.Today.Date));
com3.Parameters.Add(new OleDbParameter("", dr.GetInt32(1)));
com3.ExecuteNonQuery();
}
else
{
OleDbCommand com3 = new OleDbCommand("INSERT INTO GIC_Attendances ([Attendance_Date], [Squadron], [Number_Attended], [Number_Expected], [AddedOnSlave]) VALUES (?, ?, ?, ?, TRUE)", Program.DB_CONNECTION);
com3.Parameters.Add(new OleDbParameter("", DateTime.Today.Date));
com3.Parameters.Add(new OleDbParameter("", dr.GetInt32(1)));
com3.Parameters.Add(new OleDbParameter("", dr.GetInt32(0)));
com3.Parameters.Add(new OleDbParameter("", 4));
com3.ExecuteNonQuery();
}
dr2.Close();
}
catch
{
}
}
dr.Close();
}
答案 0 :(得分:1)
如评论中所述,您需要关闭并处理连接。拥有一个保持连接的全局变量不是一个好的模式,因为它总是很难正确地销毁变量。
你可以尝试这样的东西来证明这一点
private void update_gic_attendances()
{
using(OleDbConnection cn = new OleDbConnection(....your connection string...))
using(OleDbCommand com = new OleDbCommand(....., cn))
{
cn.Open();
.....
using(OleDbDataReader dr1 = com.ExecuteReader())
{
while(dr1.Read())
{
using(OleDbCommand com2 = new OleDbCommand(...., cn);
using(OleDbDataReader dr2 = com2.ExecuteReader())
{
....
if(dr2.HasRows)
{
using(OleDbCommand com3 = new OleDbCommand(....., cn)
{
....
com3.ExecuteNonQuery();
}
}
else
{
using(OleDbCommand com3 = new OleDbCommand(....., cn))
{
com3.ExecuteNonQuery();
}
}
}
}
}
}
}
现在连接是方法的本地连接。它被创建并包含在using语句中,该语句将在using块的出口处关闭并销毁它。而读者和命令等其他一次性物体也是如此。在此代码的末尾,连接已关闭并处理,文件不应再被锁定(除非您在某处打开了另一个连接)
但是,在你的第一个查询中,有些东西似乎不正确 您调用SELECT COUNT(*)语句,但这只返回满足查询WHERE子句的数字或记录,而不是整行。然后使用DataReader循环遍历此查询结果,最糟糕的是,您尝试为第一个和第二个字段调用GetInt32。但第二个不存在。