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

时间:2016-02-12 16:55:07

标签: python sqlite

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

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

3 个答案:

答案 0 :(得分:2)

这是我一直在使用的一个简单的解决方法:

  • 创建一个布尔标志(例如,“flagConnOpen”)以表示打开的连接 - 例如在处理数据库工作的类中。
  • 最初,flagConnOpen = False
  • 每当您想(有条件地)打开连接时,请检查此标志是否为True,如果没有,请打开连接并将标志设置为true。

e.g。

...
def OpenConn(self):
    if(self.flagConnOpen == False):
        self.db = sqlite3.connect(self.dbPath);
        self.flagConnOpen = True;

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

答案 1 :(得分:1)

1)使用<TextBox x:Name="attr_Accurate" Text="{Binding Path=SelectedItem.Attributes.Cunning), ElementName=listCharacters, Mode=OneWay}" PreviewTextInput="NumericInput"/> 检查进程是否使用了数据库文件:

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))

2)对于阅读,操作系统应该缓存文件,以便您可以阅读,如果您尝试编写,则会引发以下错误:

True  
False

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

sqlite3.connect
  

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

答案 2 :(得分:0)

“尝试...除外”效果也很好

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))

出局:错误