Python SQLite删除行

时间:2016-07-15 10:54:22

标签: python sqlite

这与其他人有类似的问题,但没有人明确解释如何纠正这个问题:

process.py

import sqlite3  # version 2.6.0

connection = sqlite3.connect('./db.sqlite')
cursor = connection.cursor()
count_before = cursor.execute('SELECT COUNT(*) FROM r_data;').fetchall()[0][0]
print('{} rows in {}'.format(count_before, table_name))

query = 'DELETE FROM r_data WHERE pk IN (501, 668);'
print('Deleted ', cursor.execute(query).rowcount, 'rows')

count_after = cursor.execute('SELECT COUNT(*) FROM r_data;').fetchall()[0][0]
print('{} rows in {}'.format(count_after, table_name))
cursor.close()
connection.close()

输出:

$ python process.py 
824 rows
822 rows
$ python process.py 
824 rows
822 rows

我知道SQL查询很好,因为我可以通过其他sqlite“客户端”成功运行它们,例如firefox sqlite manager插件。

1 个答案:

答案 0 :(得分:1)

是的,需要提交连接:

cursor.close()
connection.commit()   # <<<<< !!
connection.close()