我已经阅读了一些有关此事的相关帖子,并不太明白。发生的事情似乎是在访问数据库之后,数据库被锁定,以便可以读取,但不能写入。退出应用程序后,数据库将再次解锁。你能看到它并跟我说话,就像我无知一样,指出我处理这个问题的错误吗?
public static Partner GetOnePartner(string code)
{
Partner partner = new Partner();
SQLiteConnection connection = GroomwatchDB.GetConnection();
string sqlStatement = "SELECT * FROM partners WHERE partner_code = @partner_code";
SQLiteCommand command = new SQLiteCommand(sqlStatement, connection);
command.Parameters.Add(new SQLiteParameter("@partner_code"));
command.Parameters["@partner_code"].Value = code;
try
{
connection.Open();
SQLiteDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow);
if(reader.Read())
{
partner.Code = reader["partner_code"].ToString();
partner.Last_name = reader["last_name"].ToString();
partner.First_name = reader["first_name"].ToString();
partner.Pay_rate = (double)reader["pay_rate"];
partner.Active = reader["active"].ToString();
}
else
{
partner.Code = code;
partner.Last_name = "Not Found";
}
}
catch (SQLiteException ex)
{
throw ex;
}
finally
{
connection.Close();
}
return partner;
}
答案 0 :(得分:0)
您应该使用IDisposable
模式正确使用您的连接。
实际上,每个实现IDisposable
接口的类都需要使用using来调用。这样可以确保调用方法Dispose()
,从而清除非托管资源(并且不会以打开的文件结束):
public static Partner GetOnePartner(string code)
{
Partner partner = new Partner();
string sqlStatement = "SELECT * FROM partners WHERE partner_code = @partner_code";
using(SQLiteConnection connection = GroomwatchDB.GetConnection())
using(SQLiteCommand command = new SQLiteCommand(sqlStatement, connection))
{
command.Parameters.Add(new SQLiteParameter("@partner_code"));
command.Parameters["@partner_code"].Value = code;
connection.Open();
using(SQLiteDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.Read())
{
partner.Code = reader["partner_code"].ToString();
partner.Last_name = reader["last_name"].ToString();
partner.First_name = reader["first_name"].ToString();
partner.Pay_rate = (double)reader["pay_rate"];
partner.Active = reader["active"].ToString();
}
else
{
partner.Code = code;
partner.Last_name = "Not Found";
}
}
}
return partner;
}
参考文献: