SQLAlchemy Tutorial-The second chapter-sql the ORM of common queries

Source: Internet
Author: User
Tags sqlalchemy tutorial

Today is 2018-07-02.
Write the ORM notation for common SQL queries today.

    1. 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        })
    1. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.