2010-09-20 75 views
2

我想要拿出SQLiteDB对象,下面是它的打开/关闭代码。 这工作没有问题吗?我错过重要的东西吗?对于close(),我使用con.close()和cursor.close(),但我想知道是否需要cursor.close()。SQLite实现的打开/关闭功能

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 

回答

1

Cursor.close()上发生了什么取决于底层的数据库实现。对于SQLite,它目前可能不会关闭,但对于其他实现或未来的SQLite版本,它可能不会,因此我建议关闭Cursor对象。你可以在PEP 249找到关于Cursor.close()的更多信息。

而且,似乎是在你的代码一个错字:

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

大概应该是

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

否则你的代码看起来好像没什么问题。快乐编码:)。

+0

我改正了错字。谢谢。 – prosseek 2010-09-20 20:52:50