使用 pandas 將資料載入 SQL 資料庫

使用 Python 的 ETL 與 ELT

Jake Roach

Data Engineer

用 pandas 將資料載入 SQL 資料庫

ETL 管線,突出顯示 load 元件。

使用 Python 的 ETL 與 ELT

用 pandas 載入資料到 SQL 資料庫

資料使用者存取 SQL 資料庫。

pandas 提供 .to_sql() 將資料寫入 SQL

  • name
  • con
  • if_exists
  • index
  • index_label
使用 Python 的 ETL 與 ELT

用 pandas 將資料寫入 Postgres

# Create a connection object
connection_uri = "postgresql+psycopg2://repl:password@localhost:5432/market"
db_engine = sqlalchemy.create_engine(connection_uri)
# Use the .to_sql() method to persist data to SQL
clean_stock_data.to_sql(
    name="filtered_stock_data",
    con=db_engine, 
    if_exists="append",
    index=True,
    index_label="timestamps"
)
使用 Python 的 ETL 與 ELT

用 pandas 驗證資料持久化

驗證資料是否如預期寫入很重要。

  • 確認可查詢資料
  • 檢查筆數是否相符
  • 驗證每一列都存在
# Pull data written to SQL table
to_validate = pd.read_sql("SELECT * FROM cleaned_stock_data", db_engine)
# Validate counts, record equality, etc
...
使用 Python 的 ETL 與 ELT

一起來練習吧!

使用 Python 的 ETL 與 ELT

Preparing Video For Download...