如何使用SQLAlchemy创建新数据库?

Ana*_*thu 92 python sqlalchemy

使用SQLAlchemy,引擎创建如下:

from sqlalchemy import create_engine
engine = create_engine("postgresql://localhost/mydb")
Run Code Online (Sandbox Code Playgroud)

engine如果数据库不存在,则访问失败.如果指定的数据库不存在,是否可以告诉SQLAlchemy创建新数据库?

buh*_*htz 103

SQLAlchemy-UtilsSQLAlchemy提供自定义数据类型和各种实用程序函数.您可以使用pip安装最新的官方版本:

pip install sqlalchemy-utils
Run Code Online (Sandbox Code Playgroud)

数据库的助手包括create_database功能:

from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, create_database

engine = create_engine("postgres://localhost/mydb")
if not database_exists(engine.url):
    create_database(engine.url)

print(database_exists(engine.url))
Run Code Online (Sandbox Code Playgroud)

  • 尝试这个确切的代码块时出现此错误:`psycopg2.OperationalError:fe_sendauth:未提供密码`。使用 `"postgres://test:abc123@localhost:5432/test"` 我得到 `psycopg2.OperationalError: FATAL: password authentication failed for user "test"` (3认同)
  • 我不知道这个包的存在 - 非常感谢! (2认同)

Sin*_*ion 92

在postgres上,默认情况下通常会出现三个数据库.如果您能够以超级用户身份(例如,postgres角色)进行连接,则可以连接到postgrestemplate1数据库.默认的pg_hba.conf只允许命名的unix用户postgres使用该postgres角色,因此最简单的方法就是成为该用户.无论如何,像往常一样创建一个具有创建数据库权限的用户的引擎:

>>> engine = sqlalchemy.create_engine("postgres://postgres@/postgres")
Run Code Online (Sandbox Code Playgroud)

engine.execute()但是你不能使用,因为postgres不允许你在事务中创建数据库,而sqlalchemy总是试图在事务中运行查询.要解决这个问题,请从引擎获取基础连接:

>>> conn = engine.connect()
Run Code Online (Sandbox Code Playgroud)

但是连接仍然在事务中,因此您必须使用以下命令结束打开的事务commit:

>>> conn.execute("commit")
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用适当的PostgreSQL命令继续创建数据库.

>>> conn.execute("create database test")
>>> conn.close()
Run Code Online (Sandbox Code Playgroud)

  • 这对我很有用.作为旁注,当我执行`conn.execute('drop database DBWithCaps')时,我遇到了问题而没有识别出上限.`conn.execute('drop database"DBWithCaps"')`(带引号)工作正常. (3认同)

Eld*_*uid 9

with使用产量扩展接受的答案:

from sqlalchemy import create_engine
engine = create_engine("postgresql://localhost")

NEW_DB_NAME = 'database_name'

with engine.connect() as conn:
    conn.execute("commit")
    # Do not substitute user-supplied database names here.
    conn.execute(f"CREATE DATABASE {NEW_DB_NAME}")
Run Code Online (Sandbox Code Playgroud)


ren*_*kiy 6

通过提供isolation_level='AUTOCOMMIT'以下create_engine功能,可以避免在创建数据库时进行手动交易管理:

import sqlalchemy

with sqlalchemy.create_engine(
    'postgresql:///postgres',
    isolation_level='AUTOCOMMIT'
).connect() as connection:
    connection.execute('CREATE DATABASE my_database')
Run Code Online (Sandbox Code Playgroud)

另外,如果不确定数据库是否存在,可以通过抑制sqlalchemy.exc.ProgrammingError异常来忽略由于存在而导致的数据库创建错误:

import contextlib
import sqlalchemy.exc

with contextlib.suppress(sqlalchemy.exc.ProgrammingError):
    # creating database as above
Run Code Online (Sandbox Code Playgroud)

  • 我必须将“CREATE DATABASE my_database”包装在“sqlalchemy.sql.text(…)”中,然后这工作得很好。 (2认同)