It seems it is quite easy to retrieve the number of rows SELECT
ed with a SQL query with
cursor.execute("SELECT COUNT(*) from ...")
result=cursor.fetchone()
but how should I retrieve the number of rows by a DELETE
query?
The "rows affected" functionality is implemented via cursor.rowcount
:
cursor.execute("DELETE from ...")
result = cursor.rowcount
Demo:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With