SQLAlchemy - 方言



SQLAlchemy 使用方言系統與各種型別的資料庫進行通訊。每個資料庫都有一個相應的 DBAPI 包裝器。所有方言都需要安裝相應的 DBAPI 驅動程式。

SQLAlchemy API 中包含以下方言:

  • Firebird
  • Microsoft SQL Server
  • MySQL
  • Oracle
  • PostgreSQL
  • SQL
  • Sybase

create_engine() 函式會基於 URL 生成一個 Engine 物件。這些 URL 可以包含使用者名稱、密碼、主機名和資料庫名稱。可能還有可選的關鍵字引數用於其他配置。在某些情況下,接受檔案路徑,而在其他情況下,“資料來源名稱”會替換“主機”和“資料庫”部分。資料庫 URL 的典型形式如下:

dialect+driver://username:password@host:port/database

PostgreSQL

PostgreSQL 方言使用psycopg2作為預設 DBAPI。pg8000 也可以用作純 Python 替代方案,如下所示

# default
engine = create_engine('postgresql://scott:tiger@localhost/mydatabase')

# psycopg2
engine = create_engine('postgresql+psycopg2://scott:tiger@localhost/mydatabase')

# pg8000
engine = create_engine('postgresql+pg8000://scott:tiger@localhost/mydatabase')

MySQL

MySQL 方言使用mysql-python作為預設 DBAPI。還有許多可用的 MySQL DBAPI,例如 MySQL-connector-python,如下所示:

# default
engine = create_engine('mysql://scott:tiger@localhost/foo')

# mysql-python
engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo')

# MySQL-connector-python
engine = create_engine('mysql+mysqlconnector://scott:tiger@localhost/foo')

Oracle

Oracle 方言使用cx_oracle作為預設 DBAPI,如下所示:

engine = create_engine('oracle://scott:tiger@127.0.0.1:1521/sidname')
engine = create_engine('oracle+cx_oracle://scott:tiger@tnsname')

Microsoft SQL Server

SQL Server 方言使用pyodbc作為預設 DBAPI。pymssql 也可用。

# pyodbc
engine = create_engine('mssql+pyodbc://scott:tiger@mydsn')

# pymssql
engine = create_engine('mssql+pymssql://scott:tiger@hostname:port/dbname')

SQLite

SQLite 連線到基於檔案的資料庫,預設情況下使用 Python 內建模組sqlite3。由於 SQLite 連線到本地檔案,因此 URL 格式略有不同。“file”部分是資料庫的檔名。對於相對檔案路徑,這需要三個斜槓,如下所示:

engine = create_engine('sqlite:///foo.db')

對於絕對檔案路徑,三個斜槓後跟絕對路徑,如下所示:

engine = create_engine('sqlite:///C:\\path\\to\\foo.db')

要使用 SQLite:memory: 資料庫,請指定一個空 URL,如下所示:

engine = create_engine('sqlite://')

結論

在本教程的第一部分,我們學習瞭如何使用表示式語言執行 SQL 語句。表示式語言將 SQL 結構嵌入到 Python 程式碼中。在第二部分,我們討論了 SQLAlchemy 的物件關係對映能力。ORM API 將 SQL 表與 Python 類對映。

廣告
© . All rights reserved.