Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: retrieve number of rows affected with SQL DELETE query

Tags:

python

sqlite

It seems it is quite easy to retrieve the number of rows SELECTed 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?

like image 213
CptNemo Avatar asked Feb 11 '23 17:02

CptNemo


1 Answers

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
like image 135
alecxe Avatar answered Feb 13 '23 07:02

alecxe