当我输入这个查询: 删除邮件中id = 71的所有邮件

SQLite返回以下错误:

SQL error: database is locked

我如何解锁数据库,以便这个查询将工作?


当前回答

我在Mac OS X 10.5.7上从终端会话运行Python脚本时遇到了同样的问题。尽管我已经停止了脚本,并且终端窗口位于命令提示符处,但它在下次运行时仍然会给出这个错误。解决方案是关闭终端窗口,然后再次打开它。我觉得没道理,但奏效了。

其他回答

删除-journal文件听起来是个糟糕的主意。它允许sqlite在崩溃后将数据库回滚到一致的状态。如果在数据库处于不一致状态时删除它,则会留下一个损坏的数据库。引用sqlite站点的一个页面:

If a crash or power loss does occur and a hot journal is left on the disk, it is essential that the original database file and the hot journal remain on disk with their original names until the database file is opened by another SQLite process and rolled back. [...] We suspect that a common failure mode for SQLite recovery happens like this: A power failure occurs. After power is restored, a well-meaning user or system administrator begins looking around on the disk for damage. They see their database file named "important.data". This file is perhaps familiar to them. But after the crash, there is also a hot journal named "important.data-journal". The user then deletes the hot journal, thinking that they are helping to cleanup the system. We know of no way to prevent this other than user education.

The rollback is supposed to happen automatically the next time the database is opened, but it will fail if the process can't lock the database. As others have said, one possible reason for this is that another process currently has it open. Another possibility is a stale NFS lock, if the database is on an NFS volume. In that case, a workaround is to replace the database file with a fresh copy that isn't locked on the NFS server (mv database.db original.db; cp original.db database.db). Note that the sqlite FAQ recommends caution regarding concurrent access to databases on NFS volumes, because of buggy implementations of NFS file locking.

我无法解释为什么删除一个-journal文件会让你锁定一个数据库,而你以前不能。这是可复制的吗?

顺便说一下,-journal文件的存在并不一定意味着发生了崩溃或有要回滚的更改。Sqlite有几种不同的日志模式,在PERSIST或TRUNCATE模式下,它始终保留-journal文件,并更改内容以指示是否有要回滚的部分事务。

我发现SQLite中锁的各种状态的文档非常有用。Michael,如果您可以执行读操作,但不能对数据库执行写操作,这意味着某个进程已经获得了数据库上的保留锁,但还没有执行写操作。如果你正在使用SQLite3,有一个叫做PENDING的新锁,不允许更多的进程连接,但现有的连接仍然可以执行读取,所以如果这是问题所在,你应该看看这个锁。

我也有同样的问题。显然,回滚函数似乎用与db文件相同但没有最近更改的日志覆盖了db文件。我已经在下面的代码中实现了这一点,从那时起它一直工作得很好,而之前我的代码会因为数据库保持锁定而陷入循环。

希望这能有所帮助

我的python代码

##############
#### Defs ####
##############
def conn_exec( connection , cursor , cmd_str ):
    done        = False
    try_count   = 0.0
    while not done:
        try:
            cursor.execute( cmd_str )
            done = True
        except sqlite.IntegrityError:
            # Ignore this error because it means the item already exists in the database
            done = True
        except Exception, error:
            if try_count%60.0 == 0.0:       # print error every minute
                print "\t" , "Error executing command" , cmd_str
                print "Message:" , error

            if try_count%120.0 == 0.0:      # if waited for 2 miutes, roll back
                print "Forcing Unlock"
                connection.rollback()

            time.sleep(0.05)    
            try_count += 0.05


def conn_comit( connection ):
    done        = False
    try_count   = 0.0
    while not done:
        try:
            connection.commit()
            done = True
        except sqlite.IntegrityError:
            # Ignore this error because it means the item already exists in the database
            done = True
        except Exception, error:
            if try_count%60.0 == 0.0:       # print error every minute
                print "\t" , "Error executing command" , cmd_str
                print "Message:" , error

            if try_count%120.0 == 0.0:      # if waited for 2 miutes, roll back
                print "Forcing Unlock"
                connection.rollback()

            time.sleep(0.05)    
            try_count += 0.05       




##################
#### Run Code ####
##################
connection = sqlite.connect( db_path )
cursor = connection.cursor()
# Create tables if database does not exist
conn_exec( connection , cursor , '''CREATE TABLE IF NOT EXISTS fix (path TEXT PRIMARY KEY);''')
conn_exec( connection , cursor , '''CREATE TABLE IF NOT EXISTS tx (path TEXT PRIMARY KEY);''')
conn_exec( connection , cursor , '''CREATE TABLE IF NOT EXISTS completed (fix DATE, tx DATE);''')
conn_comit( connection )

我在谷歌Chrome浏览器中查看存储的密码时遇到了这个错误。

# ~/.config/google-chrome/Default
$ sqlite3 Login\ Data
SQLite version 3.35.5 2021-04-19 18:32:05
sqlite> .tables
Error: database is locked

如果你不是特别关心父进程,或者你不想停止当前正在使用数据库的chrome进程,只需将文件复制到其他地方。

$ cp Login\ Data ~/tmp/ld.sql
$ sqlite3 ~/tmp/ld.sql .tables
field_info              meta   sync_model_metadata   
insecure_credentials    stats                 
logins                  sync_entities_metadata

这样做将允许您读取数据库的内容,而不打扰或停止主chrome进程。

在选择重新启动选项之前,有必要看看能否找到sqlite数据库的用户。

在Linux上,可以使用fuser:

$ fuser database.db

$ fuser database.db-journal

在我的案例中,我得到了如下的回应:

philip    3556  4700  0 10:24 pts/3    00:00:01 /usr/bin/python manage.py shell

这表明我有另一个使用数据库的pid 3556 (manage.py)的Python程序。