from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
my_path="D:\\testing\\sqlite\\my_db.db" #Change the path
my_conn = create_engine("sqlite:///" + my_path)
We will use our connection string my_conn in our scripts below.
from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
q="INSERT INTO student values(null,'New Name', 'Four', 65, 'female')"
try:
r_set=my_conn.execute(q)
except SQLAlchemyError as e:
error=str(e.__dict__['orig'])
print(error)
else:
print("No of records added : ",r_set.rowcount)
print("Id of last record added : ",r_set.lastrowid)
Output
No of records added : 1
Id of last record added : 40
We used lastrowid to get id of last inserted row to the table.
from sqlalchemy.exc import SQLAlchemyError
my_data=(None,'Second Name','Five',75,'male')
q="INSERT INTO student values(?,?,?,?,?)"
try:
r_set=my_conn.execute(q,my_data)
except SQLAlchemyError as e:
error=str(e.__dict__['orig'])
print(error)
else:
print("No of records added : ",r_set.rowcount)
print("id of last record added : ",r_set.lastrowid)
from sqlalchemy.exc import SQLAlchemyError
my_data=[(None, 'Tes Qry', 'Six', 78, 'male'),
(None, 'Big John', 'Four', 55, 'female'),
(None, 'Ronald', 'Six', 89, 'female'),
(None, 'Recky', 'Six', 94, 'female'),
(None, 'Kty', 'Seven', 88, 'female')]
q="INSERT INTO student values(?,?,?,?,?)"
try:
r_set=my_conn.execute(q,my_data)
except SQLAlchemyError as e:
error=str(e.__dict__['orig'])
print(error)
else:
print("No of records added : ",r_set.rowcount)
print("No of records added : ",r_set.rowcount)
Output
5
We can’t get last inserted id or lastrowid when multiple records are added.
q="SELECT * FROM STUDENT order by id desc limit 0,10"
r_set=my_conn.execute(q)
for row in r_set:
print(row)
Add record to SQLite table using Tkinter GUI
Sqlite
Connection
delete
update
select
Order By
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.