sqlite3.Connection类继承,提交不起作用

时间:2013-03-21 19:14:32

标签: python database inheritance sqlite

这是我第一次通过类继承使用sqlite3,我遇到了一个问题,我没有得到回溯错误,但我执行的查询不会提交。我简化了我的代码

import sqlite3 as lite

class BaseModel(lite.Connection):
    def __init__(self, **args):
        lite.Connection.__init__(self, **args)  
        self.cur = self.cursor()

    def execute(self, query):
        self.cur.execute(query)




class Model(BaseModel):
    def __init__(self, **args):
        BaseModel.__init__(self, **args)

    def _new_(self):
        queries = []        
        queries.append(' '.join(['CREATE TABLE IF NOT EXISTS tb1',
                         '(id INTEGER PRIMARY KEY,',
                         'column1 TEXT,', 
                         'column2 INT)']))

        for q in queries:
            self.execute(q) # execute the queries

        self.commit()   # write changes to db   

    def tables(self):
        query = 'SELECT name FROM sqlite_master WHERE type="table" ORDER BY name' 
        results = self.execute(query) 
        return results#.fetchall()



if __name__ == '__main__':
    model = Model(database='test.db')
    model._new_()

    # Test Fails because the queries aren't being saved in the db
    # see Model.__new__ for details

    tables = model.tables() # get all tables

    print 'Tables Created:'

    if tables:
        for t in model.tables(): 
            print '\t%s' % str(t[0])
    else: print tables

1 个答案:

答案 0 :(得分:2)

您需要致电 self.commit()

self.commit() # write changes to db   

如果没有(),您只是引用方法,而不是调用它。

接下来,您的execute()函数不会返回任何内容:

def execute(self, query):
    return self.cur.execute(query)