2019年4月11日 星期四

[ Python 文章收集 ] SQLAlchemy ORM - Using Query

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: 
  1. q = session.query(mapped class)  
Following statement is also equivalent to the above given statement: 
  1. q = Query(mappedClass, session)  
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: 
  1. result = session.query(Customers).all()  
This statement is effectively equivalent to following SQL expression: 
  1. SELECT customers.id   
  2. AS customers_id, customers.name   
  3. AS customers_name, customers.address   
  4. AS customers_address, customers.email   
  5. AS customers_email  
  6. FROM customers  
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 
  1. from sqlalchemy import Column, Integer, String  
  2. from sqlalchemy import create_engine  
  3. from sqlalchemy.ext.declarative import declarative_base  
  4. from sqlalchemy.orm.session import sessionmaker  
  5.   
  6. db_string = "postgresql://postgres:@localhost/testdb"  
  7. engine = create_engine(db_string, echo=True)  
  8. Base = declarative_base()  
  9.   
  10. class Customers(Base):  
  11.     __tablename__ = 'customers'  
  12.     id = Column(Integer, primary_key=True)  
  13.     name = Column(String)  
  14.     address = Column(String)  
  15.     email = Column(String)  
  16.   
  17. Base.metadata.create_all(engine)  
  18.   
  19. Session = sessionmaker(bind = engine)  
  20. session = Session()  
  21. result = session.query(Customers).all()  
  22.   
  23. for row in result:  
  24.     print("Name: {}; Address: {}; Email: {}".format(row.name, row.address, row.email))  
The Query object also has many following useful methods. Please refer to SQLAlchemy Doc - Query API for more usage. 

Supplement 
* SQLAlchemy Doc - Query API 
This section presents the API reference for the ORM Query object. For a walkthrough of how to use this object, see Object Relational Tutorial.


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...