Sqlalchemy 简明教程

Using DELETE Expression

在上一章节中,我们已经了解了 Update 表达式的作用。我们接下来要学习的表达是 Delete

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

删除操作可以通过对目标表对象运行 delete() 方法来实现,如下面的语句中所示:

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

stmt = students.delete()

对于学生表,上面的代码行构造如下 SQL 表达式:

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

'DELETE FROM students'

但是,这将删除学生表中的所有行。通常,DELETE 查询与 WHERE 子句指定的逻辑表达式相关联。以下语句显示 where 参数:

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)

结果 SQL 表达式将有一个绑定参数,该参数将在语句执行时在运行时替换。

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'

以下代码示例将从学生表中删除那些姓为“Khanna”的行:

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('sqlite:///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()

要验证结果,请刷新 SQLiteStudio 中学生表的数据视图。

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