SQL 查询入门

Python 中的数据库入门

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

SQL 语句

  • 查询、插入、更新、删除数据
  • 创建与修改数据
Python 中的数据库入门

基础 SQL 查询

SELECT column_name FROM table_name

  • SELECT pop2008 FROM People
  • SELECT * FROM People
Python 中的数据库入门

基础 SQL 查询

from sqlalchemy import create_engine

engine = create_engine('sqlite:///census_nyc.sqlite')
connection = engine.connect()
stmt = 'SELECT * FROM people'
result_proxy = connection.execute(stmt)
results = result_proxy.fetchall()
Python 中的数据库入门

ResultProxy 与 ResultSet

result_proxy = connection.execute(stmt)

results = result_proxy.fetchall()
  • result_proxyResultProxy
  • resultsResultSet
Python 中的数据库入门

处理 ResultSet

first_row = results[0]
print(first_row)
('Illinois', 'M', 0, 89600, 95012)
print(first_row.keys())
['state', 'sex', 'age', 'pop2000', 'pop2008']
print(first_row.state)
'Illinois'
Python 中的数据库入门

用 SQLAlchemy 构建查询

  • 以 Python 方式构建 SQL 语句
  • 屏蔽不同数据库后端差异
Python 中的数据库入门

SQLAlchemy 查询

from sqlalchemy import Table, MetaData
metadata = MetaData()

census = Table('census', metadata, autoload=True, autoload_with=engine)
stmt = select([census])
results = connection.execute(stmt).fetchall()
Python 中的数据库入门

SQLAlchemy 的 select 语句

  • 需要一个或多个表或列的列表
  • 传入表将选取其中所有列
stmt = select([census])

print(stmt)
'SELECT * from CENSUS'
Python 中的数据库入门

Passons à la pratique !

Python 中的数据库入门

Preparing Video For Download...