Sqlalchemy 简明教程
SQLAlchemy Core - SQL Expressions
在本章中,我们将简要关注 SQL 表达式及其函数。
In this chapter, we will briefly focus on the SQL Expressions and their functions.
SQL 表达式是使用相对于目标表对象的对应方法构建的。例如,可以通过执行 insert() 方法来创建 INSERT 语句,如下所示:
SQL expressions are constructed using corresponding methods relative to target table object. For example, the INSERT statement is created by executing insert() method as follows −
ins = students.insert()
上述方法的结果是一个可以利用 str() 函数验证的插入对象。以下代码插入详细信息,如学生 id、名字、姓氏。
The result of above method is an insert object that can be verified by using str() function. The below code inserts details like student id, name, lastname.
'INSERT INTO students (id, name, lastname) VALUES (:id, :name, :lastname)'
可以按 values() 方法在特定字段中插入值以插入对象。其代码如下所示:
It is possible to insert value in a specific field by values() method to insert object. The code for the same is given below −
>>> ins = users.insert().values(name = 'Karan')
>>> str(ins)
'INSERT INTO users (name) VALUES (:name)'
Python 控制台上回显的 SQL 不会显示实际值(本例中为“Karan”)。SQLAlchemy 会生成一个绑定参数,它在语句的已编译表单中可见。
The SQL echoed on Python console doesn’t show the actual value (‘Karan’ in this case). Instead, SQLALchemy generates a bind parameter which is visible in compiled form of the statement.
ins.compile().params
{'name': 'Karan'}
同样, update(), delete() 和 select() 等方法分别创建 UPDATE、DELETE 和 SELECT 表达式。后面的章节中将会学习这些表达式的相关内容。
Similarly, methods like update(), delete() and select() create UPDATE, DELETE and SELECT expressions respectively. We shall learn about them in later chapters.