2

我正在尝试提出 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
4

1 回答 1

1

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

此外,您的代码中似乎有一个错字:

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

应该是

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

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

于 2010-09-20T19:21:51.133 回答