Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何检查Python中是否连接了SQLite3数据库?_Python_Sqlite - Fatal编程技术网

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

如何检查Python中是否连接了SQLite3数据库?,python,sqlite,Python,Sqlite,问题1:我有一个Python中的SQLite3连接。如何检查它是否已连接?我知道,如果sqlite3.connect()失败,会引发异常,但是如果我或某些人关闭了连接,我如何检查它并在必要时重新打开它 问题2:连接打开时,我可以在文件系统中移动文件(无法删除)。无论出于何种原因,数据库都将变成只读。如果我把它移回去,它就像什么都没发生一样工作。有人能解释一下吗?我应该在访问之前检查isfile(dbpath)吗?1)使用psutils检查进程是否使用了数据库文件: import os impor

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

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

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))
输出:

True  
False
2) 对于读取,操作系统应缓存文件,以便您可以读取,如果您尝试写入,将引发以下错误:

sqlite3.OperationalError: attempt to write a readonly database
正如您所说,在运行
sqlite3.connect之前检查
db
是否存在:

if os.path.exists(db):
不能强制
sqlite3.connect
函数不创建db文件


这是我一直在使用的一个简单的变通方法:

  • 创建一个布尔标志(比如“flagConnOpen”)来表示打开的连接——例如在处理db工作的类中
  • 最初,flagConnOpen=False
  • 每当您想要(有条件地)打开连接时,请检查此标志是否已为True,如果不是,请打开连接并将该标志设置为True
e、 g

然后,您可以将这个OpenConn()放在任何需要连接的函数的开头,它会根据需要打开一个函数。

“try…except”也可以很好地工作

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))
出局:是的

myconn.close()
print(chk_conn(myconn))
出局:错

myconn.close()
print(chk_conn(myconn))