【问题标题】:The open/close function of SQLite implementationSQLite实现的开/关功能
【发布时间】:2010-09-20 18:07:00
【问题描述】:

我正在尝试创建 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

【问题讨论】:

    标签: python pysqlite


    【解决方案1】:

    Cursor.close() 上发生的事情取决于底层数据库实现。对于 SQLite,它目前可能在不关闭的情况下工作,但对于其他实现或未来的 SQLite 版本可能不会,所以我建议关闭 Cursor 对象。您可以在 PEP 249 中找到有关 Cursor.close() 的更多信息。

    另外,您的代码中似乎有错字:

    self.connector = sqlite3.connect(self.dbFile)
    

    应该是

    self.con = sqlite3.connect(self.dbFile)
    

    否则你的代码对我来说看起来不错。快乐编码:)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-12
      • 2023-01-22
      • 2019-10-05
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2014-08-12
      • 1970-01-01
      相关资源
      最近更新 更多