python判断sqlite连接状态_如何用Python检查SQLite3数据库是否已连接?

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):You can't force the sqlite3.connect function to not create the db file.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值