Count total number of changes made after connecting SQLite to Python
Last Updated :
19 Jan, 2022
In this article, we are going to see how to count total changes since the SQLite database connection is open using Python. To get the total number of changes we use the connection object’s total_changes property.
Class Instance: sqlite3.Connection
Syntax: <connection_object>.total_changes
Return Value: Total no. of rows inserted, deleted, updated since the database connection is open.
For the demonstration purpose, we would be using person table stored in geeks.db database.
Table Definition:
CREATE TABLE person(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER NOT NULL);
Example:
Python3
import sqlite3
con = sqlite3.connect( 'c:/sqlite/db/geeks.db' )
create_table =
con.execute(create_table)
print ( "Total changes initially:" )
print (f 'total_changes = {con.total_changes}\n' )
insert_data =
con.execute(insert_data)
print ( "Total changes after inserting 5 rows:" )
print (f 'total_changes = {con.total_changes}\n' )
select_data = 'SELECT * FROM person;'
cursor = con.execute(select_data)
header = [d[ 0 ] for d in cursor.description]
print ( * header)
for row in cursor:
print ( * row)
print ()
delete_data = 'DELETE FROM person WHERE name="Tanvi";'
con.execute(delete_data)
print ( "Total changes after deleting a row:" )
print (f '\ntotal_changes = {con.total_changes}\n' )
cursor = con.execute( 'SELECT * FROM person;' )
print ( * header)
for row in cursor:
print ( * row)
print ()
con.commit()
con.close()
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...