C# SQLite Database Locked exception

现象

在查询时没有问题,但是在Insert时会报数据库被锁定。

原因分析

可能是代码某个地方连接着数据库,忘记关闭了。

解决办法

原理我还没有完全搞懂,不过根据下面的写法确实解决了问题。

在某个地方,连接处于打开状态。摆脱OpenConnection和CloseConnection改变ExecuteNonQuery这个:

using (SQLiteConnection c = new SQLiteConnection(ConnectionString))
{
    
    
    c.Open();
    using (SQLiteCommand cmd = new SQLiteCommand(sql, c))
    {
    
    
        cmd.ExecuteNonQuery();
    }
}

此外,将读取数据的方式更改为:

using (SQLiteConnection c = new SQLiteConnection(ConnectionString))
{
    
    
    c.Open();
    using (SQLiteCommand cmd = new SQLiteCommand(sql, c))
    {
    
    
        using (SQLiteDataReader rdr = cmd.ExecuteReader())
        {
    
    
            ...
        }
    }
}

不要尝试像在这里一样自行管理连接池。首先,它比您编写的代码要复杂得多,但其次,它已经在SQLiteConnection对象内部进行了处理。最后,如果你没有利用using,你就没有正确地处理这些对象,你最终会遇到像你现在看到的那样的问题。

参考

https://stackoverflow.com/questions/17592671/sqlite-database-locked-exception

猜你喜欢

转载自blog.csdn.net/lxyoucan/article/details/125916251