【发布时间】:2019-12-31 11:19:34
【问题描述】:
我有一个用 Python 2.7 编写的项目,其中主程序需要频繁访问 sqlite3 数据库以写入日志、测量结果、获取设置...
目前我有一个带有 add_log()、get_setting() 等函数的 db 模块,其中的每个函数基本上如下所示:
def add_log(logtext):
try:
db = sqlite3.connect(database_location)
except sqlite3.DatabaseError as e:
db.close() # try to gracefully close the db
return("ERROR (ADD_LOG): While opening db: {}".format(e))
try:
with db: # using context manager to automatically commit or roll back changes.
# when using the context manager, the execute function of the db should be used instead of the cursor
db.execute("insert into logs(level, source, log) values (?, ?, ?)", (level, source, logtext))
except sqlite3.DatabaseError as e:
return("ERROR (ADD_LOG): While adding log to db: {}".format(e))
return "OK"
(删除了一些额外的代码和 cmets)。
看来我应该写一个类扩展基本的sqlite连接对象功能,以便连接只创建一次(在主程序的开头),然后这个对象包含诸如
之类的功能class Db(sqlite3.Connection):
def __init__(self, db_location = database_location):
try:
self = sqlite3.connect(db_location)
return self
except sqlite3.DatabaseError as e:
self.close() # try to gracefully close the db
def add_log(self, logtext):
self.execute("insert into logs(level, source, log) values (?, ?, ?)", (level, source, logtext))
似乎这应该相当简单,但我似乎无法让它工作。
这里似乎有一些有用的建议: Python: How to successfully inherit Sqlite3.Cursor and add my customized method 但我似乎无法理解如何为我的目的使用类似的构造。
【问题讨论】:
-
您应该使用“自定义”光标而不是修改连接本身。您的“连接”尝试调用执行,这是一个 Cursor 方法。
-
莫里斯,也许我误解了你的评论,但第一个块中的代码有效。所以我实例化'db'这是一个连接,然后使用执行。我读到(某处),当使用上下文管理器“with”时,应该使用执行方法而不是游标。理想情况下,我希望我的班级(如果事实证明这是我需要的)也使用上下文管理器。
标签: python python-2.7 sqlite