English 中文(简体)
Using DELETE Expression
  • 时间:2024-12-24

Using DELETE Expression


Previous Page Next Page  

In the previous chapter, we have understood what an Update expression does. The next expression that we are going to learn is Delete.

The delete operation can be achieved by running delete() method on target table object as given in the following statement −

stmt = students.delete()

In case of students table, the above pne of code constructs a SQL expression as following −

 DELETE FROM students 

However, this will delete all rows in students table. Usually DELETE query is associated with a logical expression specified by WHERE clause. The following statement shows where parameter −

stmt = students.delete().where(students.c.id > 2)

The resultant SQL expression will have a bound parameter which will be substituted at runtime when the statement is executed.

 DELETE FROM students WHERE students.id > :id_1 

Following code example will delete those rows from students table having lastname as ‘Khanna’ −

from sqlalchemy.sql.expression import update
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
engine = create_engine( sqpte:///college.db , echo = True)

meta = MetaData()

students = Table(
    students , meta, 
   Column( id , Integer, primary_key = True), 
   Column( name , String), 
   Column( lastname , String), 
)

conn = engine.connect()
stmt = students.delete().where(students.c.lastname ==  Khanna )
conn.execute(stmt)
s = students.select()
conn.execute(s).fetchall()

To verify the result, refresh the data view of students table in SQLiteStudio.

Advertisements