过滤与定位数据

Python 中的数据库入门

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Where 子句

stmt = select([census])

stmt = stmt.where(census.columns.state == 'California')
results = connection.execute(stmt).fetchall()
for result in results: print(result.state, result.age)
California 0
California 1
California 2
California 3
California 4
California 5
...
Python 中的数据库入门

Where 子句

  • 基于布尔条件限制查询返回的数据
  • 将列与某个值或另一列比较
  • 常用比较:==<=>=!=
Python 中的数据库入门

表达式

  • 提供比简单运算符更复杂的条件
  • 如:in_()like()between()
  • 更多请见文档
  • 作为 Column 的方法提供
Python 中的数据库入门

表达式

stmt = select([census])

stmt = stmt.where(census.columns.state.startswith('New'))
for result in connection.execute(stmt): print(result.state, result.pop2000)
New Jersey 56983
New Jersey 56686
New Jersey 57011
...
Python 中的数据库入门

连接词

  • 允许在 where 子句中使用多个条件
  • 如:and_()or_()not_()
Python 中的数据库入门

连接词

from sqlalchemy import or_

stmt = select([census])
stmt = stmt.where( or_(census.columns.state == 'California', census.columns.state == 'New York' ) )
for result in connection.execute(stmt): print(result.state, result.sex)
New York M
...
California F
Python 中的数据库入门

开始练习!

Python 中的数据库入门

Preparing Video For Download...