連線到 PostgreSQL 資料庫
在這些練習中,你會連線到由 Amazon Web Services(AWS)雲端託管的真實資料庫!
先從連線到 PostgreSQL 資料庫開始。連線 PostgreSQL 時,許多人偏好使用 psycopg2 資料庫驅動程式,因為它高效支援幾乎所有 PostgreSQL 功能,且是 SQLAlchemy 中對應 PostgreSQL 的標準方言。
你可能還記得在第 1 章中,我們使用 create_engine() 函式與連線字串來連線到資料庫。一般而言,連線字串的格式為 "dialect+driver://username:password@host:port/database"
本練習的連線字串有三個部分:方言與驅動('postgresql+psycopg2://'),接著是使用者名稱與密碼('student:datacamp'),再來是主機與連接埠('@postgresql.csrrinzqubik.us-east-1.rds.amazonaws.com:5432/'),最後是資料庫名稱('census')。你需要將此字串作為引數傳給 create_engine(),才能連線到資料庫。
本練習屬於課程
Python 資料庫入門
練習說明
- 從
sqlalchemy匯入create_engine。 - 透過串接下列字串建立連到
census資料庫的 engine:'postgresql+psycopg2://''student:datacamp''@postgresql.csrrinzqubik.us-east-1.rds.amazonaws.com'':5432/census'
- 在
engine上使用.table_names()方法來印出資料表名稱。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import create_engine function
from ____ import create_engine
# Create an engine to the census database
engine = create_engine(____)
# Use the .table_names() method on the engine to print the table names
print(____)