Python:检索受SQL DELETE查询影响的行数

时间:2015-03-11 05:04:50

标签: python sqlite

使用

检索带有SQL查询的行数SELECT是非常容易的
cursor.execute("SELECT COUNT(*) from ...")
result=cursor.fetchone()

但是如何通过DELETE查询检索行数?

1 个答案:

答案 0 :(得分:6)

"行受影响"功能通过cursor.rowcount实现:

cursor.execute("DELETE from ...")
result = cursor.rowcount

演示:

In [1]: import sqlite3

In [2]: db = sqlite3.connect(":memory:")

In [3]: cursor = db.cursor()

In [4]: cursor.execute("create table test(i)")
Out[4]: <sqlite3.Cursor at 0x103a3c260>

In [5]: cursor.execute("insert into test(i) values (1)")
Out[5]: <sqlite3.Cursor at 0x103a3c260>

In [6]: cursor.execute("insert into test(i) values (2)")
Out[6]: <sqlite3.Cursor at 0x103a3c260>

In [7]: cursor.execute("insert into test(i) values (3)")
Out[7]: <sqlite3.Cursor at 0x103a3c260>

In [8]: cursor.execute("delete from test where i >= 2")
Out[8]: <sqlite3.Cursor at 0x103a3c260>

In [9]: cursor.rowcount
Out[9]: 2