我正在尝试创建 SQLiteDB 对象,下面是它的打开/关闭代码。 这工作没有问题吗?我错过了什么重要的东西吗?
对于 close(),我使用了 con.close() 和 cursor.close(),但我想知道是否需要 cursor.close()。
class SQLiteDB(object):
def __init__(self, dbFile, connect = True):
self.dbFile = dbFile
self.con = None
self.cursor = None
if connect:
self.open()
def __del__(self):
if self.con:
self.close()
def open(self):
self.con = sqlite3.connect(self.dbFile)
self.cursor = self.connector.cursor()
return self.con, self.cursor
def close(self):
self.con.close()
self.cursor.close()
self.cursor = None
self.con = None
请您参考如下方法:
在 Cursor.close() 上发生的事情取决于底层数据库的实现。对于 SQLite,它目前可能在不关闭的情况下工作,但对于其他实现或 future 的 SQLite 版本,它可能不会,所以我建议关闭 Cursor 对象。您可以在 PEP 249 中找到有关 Cursor.close() 的更多信息。 .
此外,您的代码中似乎有一个拼写错误:
self.connector = sqlite3.connect(self.dbFile)
应该是
self.con = sqlite3.connect(self.dbFile)
否则你的代码对我来说没问题。编码愉快 :) .
