SQLAlchemy Core Delete


This entry is part 6 of 6 in the series SQLAlchemy

Continuing on with the same database and table, we will delete records. If we were using SQL we would write something like the following to do a simple delete to our Employees table in the D:\Test\emp4.db SQLite database. We have a table called Employees. It has three columns: id, name and position.

DELETE FROM Employees
DELETE FROM Employees WHERE id=1

{python]
# SQLAlchemy Core
table.delete().where(table.c.id > 2)
[/python]

Python Project

import sqlalchemy as sa
engine = sa.create_engine(r'sqlite:///D:\Test\emp4.db') 
connection = engine.connect()

meta_data = sa.MetaData()
employees = sa.Table('Employees', meta_data, autoload_with=engine)
delete_query = employees.delete().where(employees.c.id==4) # hugh the janitor is 4
print(delete_query)
DELETE FROM "Employees" WHERE "Employees".id = :id_1
connection.execute(delete_query)
<sqlalchemy.engine.cursor.LegacyCursorResult at 0x156b3d3d5d0>
Series Navigation<< SQLAlchemy Core Update

Leave a Reply