Today is 2018-07-02.
Write the ORM notation for common SQL queries today.
- The EMP, which is the model of the employee table, is first mended.
class Emp(Base): __tablename__ = ‘emp‘ empno = Column(Integer, primary_key=True) ename = Column(String(10)) job = Column(String(9)) mgr = Column(Integer) hiredate = Column(Date) comm = Column(DECIMAL(7, 2)) deptno = Column(Integer, ForeignKey(‘dept.deptno‘)) def __repr__(self): # 定义这个方法是为了方便打印到控制台查看. return str({ ‘empno‘: self.empno, ‘ename‘: self.ename, ‘job‘: self.job, ‘deptno‘: self.deptno })
- Next, let's make some basic queries.
from models import *def query_emp(): emp1 = sess.query(Emp).first() print(emp1)# 查询名字叫Smith的员工def query_emp_with_filter(): emp1 = sess.query(Emp).filter(Emp.ename == ‘Smith‘).first() print(emp1)# 查询名字叫Smith, 职务为CLERK的一个员工def query_emp_with_filters(): emp1 = sess.query(Emp).filter(Emp.ename == ‘Smith‘, Emp.job == ‘CLERK‘).first() print(emp1)# 查询职务为CLERK的全部员工def query_emp_all_clerks(): emp_clerks = sess.query(Emp).filter(Emp.job == ‘CLERK‘).all() for clerk in emp_clerks: print(clerk)# 查询员工的名字和工号, 并按入职日期排序def query_emp_empno_ename_order_by_hiredate(): emps = sess.query(Emp.empno, Emp.ename, Emp.job, Emp.hiredate).order_by(Emp.hiredate.asc()).all() for item in emps: print(item.empno, item.ename, item.job, item.hiredate)if __name__ == ‘__main__‘: query_emp_empno_ename_order_by_hiredate()
Today is limited to time, first so much. The explanation is very poor, the classmate has the question, please leave a message.
SQLAlchemy official website
Http://docs.sqlalchemy.org/en/latest/contents.html
Tutorials All code GitHub address
Https://github.com/notfresh/sqlalchemy_demo
SQLAlchemy Tutorial-The second chapter-sql the ORM of common queries