如何检查 SQLite3 数据库是否在 Python 中连接?

Fab*_*ian 7 python sqlite

问题 1:我在 Python 中有一个 SQLite3 连接。如何检查它是否已连接?我知道如果 sqlite3.connect() 失败,则会引发异常,但是如果我或某些人关闭了连接,我该如何检查并在必要时重新打开它?

问题 2:我可以在连接打开时移动文件系统中的文件(无法删除)。无论出于何种原因,数据库随后变为只读。如果我把它移回去,它就好像什么都没发生一样。有人可以解释一下吗?我应该在访问前检查 isfile(dbpath) 吗?

小智 9

“尝试...除了”也很有效

import sqlite3 as mdb
def chk_conn(conn):
     try:
        conn.cursor()
        return True
     except Exception as ex:
        return False

myconn = mdb.connect('test.db')
print(chk_conn(myconn))
Run Code Online (Sandbox Code Playgroud)

输出:正确

myconn.close()
print(chk_conn(myconn))
Run Code Online (Sandbox Code Playgroud)

出:假


Ken*_*nly 4

  1. 用于psutils检查数据库文件是否被进程使用:
import os
import psutil
import sqlite3

con = sqlite3.connect("temp.db")

def is_open(path):
    for proc in psutil.process_iter():
        try:
            files = proc.get_open_files()
            if files:
                for _file in files:
                    if _file.path == path:
                        return True
        except psutil.NoSuchProcess as err:
            print(err)
    return False

con = sqlite3.connect("temp.db")
path = os.path.abspath("temp.db")
print(is_open(path))
con.close()
print(is_open(path))
Run Code Online (Sandbox Code Playgroud)

输出:

True  
False
Run Code Online (Sandbox Code Playgroud)
  1. 对于读取,操作系统应该缓存该文件,以便您可以读取,如果您尝试写入,则会引发以下错误:

    sqlite3.OperationalError:尝试写入只读数据库

db正如您所说,在运行之前检查是否存在sqlite3.connect

if os.path.exists(db):
Run Code Online (Sandbox Code Playgroud)

您不能强制该sqlite3.connect函数不创建 db 文件。