为什么在读取光标对象时会多出一行?

时间:2016-12-02 20:16:25

标签: python python-2.7 sqlite

为什么我在运行SELECT语句和UPDATE后会在3行表中获得4行?

下面是一个初始表,我使用的是SQLite 3 v3.11.0:

animal  isMammal
------- ------- 
cat     1
dog     1
salmon  0

当我在test()函数中评论第二行时,我得到:

(u'cat', 1)
(u'dog', 1)

这完全没问题(我只是在寻找哺乳动物),但是当我在打印光标之前制作鲑鱼哺乳动物时,我得到了:

(u'cat', 1)
(u'cat', 1)
(u'dog', 1)
(u'salmon', 1)

对我来说这很奇怪......

import sqlite3


class DB:
    conn = None

    def connect(self):
        self.conn = sqlite3.connect('./database.db')

    def query(self, sql):
        try:
            cursor = self.conn.cursor()
            cursor.execute(sql)
        except (AttributeError, sqlite3.OperationalError) as e:
            self.connect()
            cursor = self.conn.cursor()
            cursor.execute(sql)
        return cursor

    def query_many(self, sql, data):
        try:
            cursor = self.conn.cursor()
            cursor.executemany(sql, data)
        except (AttributeError, sqlite3.OperationalError) as e:
            self.connect()
            cursor = self.conn.cursor()
            cursor.executemany(sql, data)
        return cursor

    def commit(self):
        self.conn.commit()


def populate_table(db):
    data = [('cat', 1), ('dog', 1), ('salmon', 0)]
    sql = 'INSERT INTO animals VALUES (?,?)'
    db.query_many(sql, data)
    db.commit()


def create_table(db):    
    # Drop table if exist
    sql = '''DROP TABLE IF EXISTS animals'''
    db.query(sql)
    db.commit()

    # Create animals table
    sql = '''
        CREATE TABLE animals(
            animal text unique PRIMARY KEY, 
            isMammal boolean default 0
        )'''
    db.query(sql)
    db.commit()


def test(db):
    cur = db.query('SELECT * FROM animals WHERE isMammal=1') 
    db.query('UPDATE animals SET isMammal=1 WHERE isMammal=0') # w/o this line I got 2 rows
    db.commit()

    # I expect here to print mammals only
    for row in cur:
        print row

if __name__ == '__main__':
    db = DB()
    create_table(db)
    populate_table(db)
    test(db)

0 个答案:

没有答案