Your cart is currently empty!
Author: alien
-
Khóa học miễn phí Using Query nhận dự án làm có lương
SQLAlchemy ORM – 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)
Following statement is also equivalent to the above given statement −
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 −
result = session.query(Customers).all()
This statement is effectively equivalent to following SQL expression −
SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email 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 −
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 console shows list of records as below −
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
The Query object also has following useful methods −
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.
Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc
Khóa học miễn phí Creating Session nhận dự án làm có lương
SQLAlchemy ORM – Creating Session
In order to interact with the database, we need to obtain its handle. A session object is the handle to database. Session class is defined using sessionmaker() – a configurable session factory method which is bound to the engine object created earlier.
from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind = engine)
The session object is then set up using its default constructor as follows −
session = Session()
Some of the frequently required methods of session class are listed below −
Sr.No. | Method & Description |
---|---|
1 |
begin() begins a transaction on this session |
2 |
add() places an object in the session. Its state is persisted in the database on next flush operation |
3 |
add_all() adds a collection of objects to the session |
4 |
commit() flushes all items and any transaction in progress |
5 |
delete() marks a transaction as deleted |
6 |
execute() executes a SQL expression |
7 |
expire() marks attributes of an instance as out of date |
8 |
flush() flushes all object changes to the database |
9 |
invalidate() closes the session using connection invalidation |
10 |
rollback() rolls back the current transaction in progress |
11 |
close() Closes current session by clearing all items and ending any transaction in progress |
Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc