今天是2018-07-02.
今天来写一些常用的SQL查询的ORM写法.
- 先把Emp, 也就是员工表的模型补上.
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
})
- 接下来, 我们进行一些基本的查询.
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()
今天限于时间, 先这么多. 讲解比较粗劣, 各位同学有问题, 请留言.
SQLAlchemy官方网站
http://docs.sqlalchemy.org/en/latest/contents.html
教程全部代码github地址
https://github.com/notfresh/sqlalchemy_demo
原文地址:https://www.cnblogs.com/notfresh/p/9256350.html
时间: 2024-10-11 17:54:56