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

SQLite返回以下错误:

SQL error: database is locked

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


当前回答

我的Linux环境上的lsof命令帮助我弄清楚一个进程挂起并保持文件打开。 终止了这个过程,问题就解决了。

其他回答

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

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

如果你想删除一个“database is locked”错误,请按照以下步骤执行:

将数据库文件复制到其他位置。 用复制的数据库替换数据库。这将解除对访问数据库文件的所有进程的引用。

我也有同样的问题。显然,回滚函数似乎用与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 )

我只是犯了同样的错误。 5分钟后,我发现我没有关闭一个shell巫婆正在使用db。 请关闭它,再试一次;)