连接到你的数据库

Python 中的数据库入门

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

认识 SQLAlchemy

  • 两大组件
    • Core(关系模型)
    • ORM(用户数据模型)
Python 中的数据库入门

数据库类型很多

  • SQLite
  • PostgreSQL
  • MySQL
  • Microsoft SQL Server
  • Oracle SQL
  • 还有更多
Python 中的数据库入门

连接到数据库

from sqlalchemy import create_engine

engine = create_engine('sqlite:///census_nyc.sqlite')
connection = engine.connect()
  • Engine:SQLAlchemy 连接数据库的通用接口
  • 连接字符串:定位数据库所需的全部信息(含登录信息,如需)
Python 中的数据库入门

关于连接字符串的一点说明

驱动与方言

        Driver + Dialect

Python 中的数据库入门

关于连接字符串的一点说明

文件名

                                                                                               文件名

Python 中的数据库入门

数据库里有什么?

在查询前,先了解数据库内容:例如有哪些表:

from sqlalchemy import create_engine

engine = create_engine('sqlite:///census_nyc.sqlite')
print(engine.table_names())
['census', 'state_fact']
Python 中的数据库入门

反射(Reflection)

反射读取数据库并构建 SQLAlchemy 的 Table 对象

from sqlalchemy import MetaData, Table

metadata = MetaData()
census = Table('census', metadata, autoload=True, autoload_with=engine)
print(repr(census))
Table('census', MetaData(bind=None), Column('state', VARCHAR(
length=30), table=<census>), Column('sex', VARCHAR(length=1),
table=<census>), Column('age', INTEGER(), table=<census>),
Column('pop2000', INTEGER(), table=<census>), Column('pop2008',
INTEGER(), table=<census>), schema=None)
Python 中的数据库入门

开始练习!

Python 中的数据库入门

Preparing Video For Download...