Source From Here
Using Query
All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it. Query objects are initially generated using the query() method of the Session as follows:
Following statement is also equivalent to the above given statement:
The
query object has all() method which returns a resultset in the form of list of objects. If we execute it on our customers table:
This statement is effectively equivalent to following SQL expression:
The result object can be traversed using For loop as below to obtain all records in underlying customers table. Here is the complete code to display all records in
Customers table
- demo22.py
The
Query object also has many following useful methods. Please refer to SQLAlchemy Doc - Query API for more usage.
Supplement
* SQLAlchemy Doc - Query API
Using Query
All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it. Query objects are initially generated using the query() method of the Session as follows:
- q = session.query(mapped class)
- q = Query(mappedClass, session)
- result = session.query(Customers).all()
- SELECT customers.id
- AS customers_id, customers.name
- AS customers_name, customers.address
- AS customers_address, customers.email
- AS customers_email
- FROM customers
- demo22.py
- from sqlalchemy import Column, Integer, String
- from sqlalchemy import create_engine
- from sqlalchemy.ext.declarative import declarative_base
- from sqlalchemy.orm.session import sessionmaker
- db_string = "postgresql://postgres:
@localhost/testdb" - engine = create_engine(db_string, echo=True)
- Base = declarative_base()
- class Customers(Base):
- __tablename__ = 'customers'
- id = Column(Integer, primary_key=True)
- name = Column(String)
- address = Column(String)
- email = Column(String)
- Base.metadata.create_all(engine)
- Session = sessionmaker(bind = engine)
- session = Session()
- result = session.query(Customers).all()
- for row in result:
- print("Name: {}; Address: {}; Email: {}".format(row.name, row.address, row.email))
Supplement
* SQLAlchemy Doc - Query API
沒有留言:
張貼留言