Engine 與連線字串
好了,現在要建立你的第一個 engine!Engine 是與資料庫互動的通用介面,而它連線所需的資訊會放在連線字串中,例如 sqlite:///example.sqlite。其中,sqlite:/// 裡的 sqlite 是資料庫驅動程式(driver),而 example.sqlite 則是位在本機目錄中的 SQLite 檔案。
想更深入了解連線字串,可以參考 SQLAlchemy 說明文件。
在這個練習中,你的工作是建立一個能連到本機 SQLite 檔案 census.sqlite 的 engine。接著,用 .table_names() 方法列印出該 engine 所包含的資料表名稱。注意:如果只是要列印資料表名稱,建立 engine 之後不需要再呼叫 engine.connect()。
本練習屬於課程
Python 資料庫入門
練習說明
- 從
sqlalchemy模組匯入create_engine。 - 使用
create_engine()函式,建立一個以sqlite為驅動程式、連到本機檔案census.sqlite的 engine。請務必將連線字串用引號括起來。 - 列印
engine上.table_names()方法的輸出。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import create_engine
# Create an engine that connects to the census.sqlite file: engine
engine = ____
# Print table names
print(____)