📜  SQLAlchemy ORM-使用查询

📅  最后修改于: 2020-11-27 07:44:49             🧑  作者: Mango


SQLAlchemy ORM生成的所有SELECT语句均由Query对象构造。它提供了一个生成接口,因此,后续调用将返回一个新的Query对象,该对象是前者的副本,并带有其他条件和与之相关的选项。

最初使用Session的query()方法生成查询对象,如下所示:

q = session.query(mapped class)

以下语句也等同于上述给定语句-

q = Query(mappedClass, session)

查询对象具有all()方法,该方法以对象列表的形式返回结果集。如果我们在客户表上执行它-

result = session.query(Customers).all()

该语句实际上等效于以下SQL表达式-

SELECT customers.id 
AS customers_id, customers.name 
AS customers_name, customers.address 
AS customers_address, customers.email 
AS customers_email
FROM customers

可以使用如下所示的For循环遍历结果对象,以获取基础客户表中的所有记录。这是显示客户表中所有记录的完整代码-

from sqlalchemy import Column, Integer, String
from sqlalchemy import create_engine
engine = create_engine('sqlite:///sales.db', echo = True)
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class Customers(Base):
   __tablename__ = 'customers'
   id = Column(Integer, primary_key =  True)
   name = Column(String)

   address = Column(String)
   email = Column(String)

from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind = engine)
session = Session()
result = session.query(Customers).all()

for row in result:
   print ("Name: ",row.name, "Address:",row.address, "Email:",row.email)

Python控制台显示记录列表,如下所示-

Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com
Name: Komal Pande Address: Koti, Hyderabad Email: komal@gmail.com
Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com
Name: S.M.Krishna Address: Budhwar Peth, Pune Email: smk@gmail.com

Query对象还具有以下有用的方法-

Sr.No. Method & Description
1

add_columns()

It adds one or more column expressions to the list of result columns to be returned.

2

add_entity()

It adds a mapped entity to the list of result columns to be returned.

3

count()

It returns a count of rows this Query would return.

4

delete()

It performs a bulk delete query. Deletes rows matched by this query from the database.

5

distinct()

It applies a DISTINCT clause to the query and return the newly resulting Query.

6

filter()

It applies the given filtering criterion to a copy of this Query, using SQL expressions.

7

first()

It returns the first result of this Query or None if the result doesn’t contain any row.

8

get()

It returns an instance based on the given primary key identifier providing direct access to the identity map of the owning Session.

9

group_by()

It applies one or more GROUP BY criterion to the query and return the newly resulting Query

10

join()

It creates a SQL JOIN against this Query object’s criterion and apply generatively, returning the newly resulting Query.

11

one()

It returns exactly one result or raise an exception.

12

order_by()

It applies one or more ORDER BY criterion to the query and returns the newly resulting Query.

13

update()

It performs a bulk update query and updates rows matched by this query in the database.