SQLAlchemy教程

SQLAlchemy 方言

SQLAlchemy 使用方言系统与各种类型的数据库进行通信。每个数据库都有一个对应的 DBAPI 包装器。所有方言都需要安装适当的 DBAPI 驱动程序。
SQLAlchemy API 中包含以下方言-
Firebird Microsoft SQL Server MySQL Oracle PostgreSQL SQL Sybase
基于 URL 的 Engine 对象由 create_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')

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 格式略有不同。 URL 的"file"部分是数据库的文件名。对于相对文件路径,这需要三个斜杠,如下所示-
engine = create_engine('sqlite:///foo.db')
对于绝对文件路径,三个斜杠后跟绝对路径,如下所示-
engine = create_engine('sqlite:///C:\\path\\to\\foo.db')
要使用 SQLite:memory:database,请指定一个空 URL,如下所示-
engine = create_engine('sqlite://')

结论

在本教程的第一部分,我们学习了如何使用表达式语言来执行 SQL 语句。表达式语言在 Python 代码中嵌入了 SQL 结构。在第二部分,我们讨论了 SQLAlchemy 的对象关系映射能力。 ORM API 将 SQL 表映射到 Python 类。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4