連線到你的資料庫

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 資料庫入門

談談連線字串

driverdialect.png

        Driver + Dialect

Python 資料庫入門

談談連線字串

filename.png

                                                                                               檔名

Python 資料庫入門

資料庫裡有什麼?

在查詢資料庫前,你需要先知道裡面有什麼,例如有哪些資料表:

from sqlalchemy import create_engine

engine = create_engine('sqlite:///census_nyc.sqlite')
print(engine.table_names())
['census', 'state_fact']
Python 資料庫入門

Reflection

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...