2010-09-20 115 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