SQLite:数据库被锁定C#


编辑!这是错误的视频https://www.youtube.com/watch?v=_mJ3o3ykQrw

在我的数据库处理程序类中创建了一个名为AddAttendance的方法。我可以从其他类访问它,因为它是静态的。这是代码:

public static void AddAttendance(string ID, string DateTime, string Action, string Session)
{
SQLiteConnection sqlite_conn = new SQLiteConnection("Data Source = " + database + "; Version = 3; New = True; Compress = True;");
try
{
sqlite_conn.Open();
SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
sqlite_cmd.CommandText = "INSERT INTO AttendanceLog (UserID, DateTime, Action, Session) VALUES (" +
"'" + ID + "', '" + DateTime + "', '" + Action + "', '" + Session + "');";
sqlite_cmd.ExecuteNonQuery();
sqlite_conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
sqlite_conn.Close();
}

此代码只能由我绑定到按钮的对话框窗体访问:

private void buttonAccept_Click(object sender, EventArgs e)
{
if (textBoxID.Text.Length == 0 || textBoxTimeDate.Text.Length == 0)
{
MessageBox.Show("ID or Time and Date cannot be empty!", "Missing field", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (buttonAccept.Text.Equals("Accept"))
{
buttonAccept.Text = "Confirm!";
return;
}
DatabaseHandles.AddAttendance(textBoxID.Text, textBoxTimeDate.Text, comboBoxAction.Text, comboBoxSession.Text);
MessageBox.Show("Record added!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
}

如果我从我的Form Kiosk模式访问它,它运行得很好,但如果我从其他地方访问,它会报告数据库被锁定。

奇怪的是,当我事先先将其访问到我的Kiosk模式,然后访问到其他地方时,它运行得很好。

我不知道我错过了什么。这里是我调用表单时使用的相同代码:

AttendanceInsert ai = new AttendanceInsert();
ai.ShowDialog(); 

罪魁祸首是读取器,尽管我用using参数关闭了所有连接,但我忘记关闭我使用的所有读取器,我应该在这里也使用using,但你明白了。数据库已锁定,读取器未关闭

public static void LoadScannedUser(string ID)
{
string sql = "SELECT * FROM Users WHERE ID = '" + ID + "'";
using (var conn = new SQLiteConnection(ConnectionString))
{
using (var cmd = conn.CreateCommand())
{

try
{
cmd.CommandText = sql;
conn.Open();
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
scannedUser.ID = reader.GetString(1);
scannedUser.Password = reader.GetString(2);
scannedUser.PPicture = Cryptorizer.Base64ToImage(reader.GetString(3));
scannedUser.FName = reader.GetString(4);
scannedUser.MName = reader.GetString(5);
scannedUser.LName = reader.GetString(6);
scannedUser.Agency = reader.GetString(7);
scannedUser.Position = reader.GetString(8);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}

我不知道它是否能解决你的问题,但没有理由不做对:

public static void AddAttendance(string id, string datetime, string action, string session)
{
try
{
using (var sqlite_conn = new SQLiteConnection("Data Source = " + database + "; Version = 3; New = True; Compress = True;")
{
sqlite_conn.Open();
using (var sqlite_cmd = sqlite_conn.CreateCommand())
{ 
sqlite_cmd.CommandText = "INSERT INTO AttendanceLog (UserID, DateTime, Action, Session) VALUES (@Id, @DateTime, @Action, @Session);";
sqlite_cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.NVarChar)).Value = id;
sqlite_cmd.Parameters.Add(new SqlParameter("DateTime", SqlDbType.NVarChar)).Value = datetime;
sqlite_cmd.Parameters.Add(new SqlParameter("Action", SqlDbType.NVarChar)).Value = action;
sqlite_cmd.Parameters.Add(new SqlParameter("Session", SqlDbType.NVarChar)).Value = session;
sqlite_cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

通过这种方式,您的连接和SqlCommand将被关闭和处理,并且您正在使用参数化查询,这将阻止SQL注入。如果您的数据库列不是NVarChar,则需要更改它。还可以为参数定义添加长度。

此锁定问题源于尝试重用数据库连接。ADO.Net有一个称为连接池的功能,因此在整个应用程序中重复使用同一个连接对象是一个非常糟糕的想法,这实际上会使的速度变慢,此外还会导致类似的锁定问题。

相反,您确实应该为大多数查询创建一个全新的连接对象,在运行查询之前立即打开连接,并在查询完成后立即处理对象。实现这一点的最简单方法是通过using块:

private static string ConnectionString {get;} = "Data Source = " + database + "; Version = 3; New = True; Compress = True;"
public static void AddAttendance(string ID, string dateTime, string Action, string Session)
{
string sql = "INSERT INTO AttendanceLog (UserID, DateTime, Action, Session) VALUES (@id, @time, @action, @session);";
using (var conn = new SQLiteConnection(ConnectionString))
using (var cmd = new SQLiteCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@id", ID);
// Note the DateTime format. It's necessary to store date values in this way in order to preserve cardinality and allow indexes and date math to function properly.
// Better DB platforms would have a DateTime type to use instead
cmd.Parameters.AddWithValue("@time", DateTime.Parse(dateTime).ToString("yyyy-MM-dd HH:mm:ss"));
cmd.Parameters.AddWithValue("@action", Action);
cmd.Parameters.AddWithValue("@session", session);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

using块将确保连接正确关闭,即使在可能错过sqllite_conn.Close()调用的情况下也是如此。


事情是这样的:修复这一个查询是不够的

您必须修复ALL查询才能依赖using块,否则仍有锁定风险。锁定问题不会显示在实际导致锁定的查询上,而是在数据库被锁定后运行的查询。

在这种情况下,看起来锁定问题可能发生在显示网格的位置。网格查询运行起来很有趣,不会显示任何错误,但不会释放其锁,因此在尝试添加记录时会出现错误,因为这是之后的下一个查询。

参数也是如此。仅此查询使用查询参数而不是字符串串联是不够的。每次将数据替换为SQL字符串时,都必须执行此操作,在每个查询中。

最新更新