基本語法
以下介紹使用 SQLAlchemy 連結資料庫的基本語法。
1
2
3
4
5
6
7
8
9
10
engine = create_engine('postgresql://myuser:mypassword@172.17.0.3:5432/mydatabase', echo=True)
Base = declarative_base()
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
建立資料庫引擎
1
engine = create_engine('postgresql://myuser:mypassword@172.17.0.3:5432/mydatabase', echo=True)
create_engine 函數用來建立與資料庫的連接。
postgresql://myuser:mypassword@172.17.0.3:5432/mydatabase 是資料庫的 URL,包含了 資料庫類型 (postgresql) 使用者名稱 (myuser) 密碼 (mypassword) 資料庫伺服器的 IP 地址 (172.17.0.3) 資料庫伺服器的端口號 (5432) 資料庫名稱 (mydatabase) echo=True 用來啟用 SQLAlchemy 的日誌功能,這樣可以在標準輸出中看到生成的 SQL 語句。
建立基礎類
Base = declarative_base() declarative_base 函數返回一個基礎類,所有 ORM 類都應該繼承這個基礎類。 這個基礎類包含了與 SQLAlchemy 互動所需的所有元數據和方法。
建立所有表
Base.metadata.create_all(engine) Base.metadata.create_all(engine) 會檢查 Base 上定義的所有 ORM 類,並在資料庫中創建相應的表。 engine 提供了資料庫的連接資訊,用於執行這些創建表的操作。
建立會話工廠
Session = sessionmaker(bind=engine) sessionmaker 是 SQLAlchemy 提供的一個函數,用來創建新的 Session 類。 bind=engine 指定這些會話應該使用哪個資料庫引擎進行連接。
建立會話
session = Session() Session() 創建了一個新的會話實例,這個會話實例用來與資料庫進行互動。 會話對象用於提交和查詢資料,並管理資料庫連接的生命週期。 總結來說,這段代碼設定了與 PostgreSQL 資料庫的連接,定義了一個基礎類用來創建 ORM 類,創建了資料庫中的所有表,並建立了一個會話實例用來進行後續的資料庫操作。
