使用 pandas 将数据加载到 SQL 数据库

Python 中的 ETL 与 ELT

Jake Roach

Data Engineer

用 pandas 将数据加载到 SQL 数据库

突出显示加载环节的 ETL 流水线。

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