SQLite实现的打开/关闭功能
我试图提出 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
I'm trying to come up with SQLiteDB object, and following is the open/close code for it.
Does this work without problem? Am I missing something important?
For close(), I use con.close() and cursor.close(), but I'm wondering if cursor.close() is necessary.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Cursor.close() 上发生的情况取决于底层数据库实现。对于 SQLite,它当前可能无需关闭即可工作,但对于其他实现或未来的 SQLite 版本,它可能不会,因此我建议关闭 Cursor 对象。您可以在 PEP 249 中找到有关 Cursor.close() 的更多信息。
另外,您的代码中似乎有一个拼写错误:
可能应该是
否则您的代码对我来说看起来很好。快乐编码:)。
What happens on Cursor.close() depends on the underlying database implementation. For SQLite it might currently work without closing, but for other implementations or a future SQLite version it might not, so I would recommend to close the Cursor object. You can find further information on Cursor.close() in PEP 249.
Also, there seems to be a typo in your code:
should probably be
Otherwise your code looks fine to me. Happy coding :) .