📜  SQLAlchemy-方言

📅  最后修改于: 2020-11-27 07:56:34             🧑  作者: Mango


SQLAlchemy使用方言系统与各种类型的数据库进行通信。每个数据库都有一个对应的DBAPI包装器。所有方言都要求安装适当的DBAPI驱动程序。

以下方言包含在SQLAlchemy API中-

  • 火鸟
  • Microsoft SQL服务器
  • 的MySQL
  • 甲骨文
  • 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方言使用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服务器

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的“文件”部分是数据库的文件名。对于相对文件路径,这需要三个斜杠,如下所示:

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

对于绝对文件路径,三个斜杠后跟绝对路径,如下所示:

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

要使用SQLite:memory:database,请指定一个空URL,如下所示-

engine = create_engine('sqlite://')

结论

在本教程的第一部分中,我们学习了如何使用表达式语言执行SQL语句。表达式语言将SQL构造嵌入Python代码中。在第二部分中,我们讨论了SQLAlchemy的对象关系映射功能。 ORM API用Python类映射SQL表。