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-Utils为SQLAlchemy提供自定义数据类型和各种实用程序函数.您可以使用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)
Sin*_*ion 92
在postgres上,默认情况下通常会出现三个数据库.如果您能够以超级用户身份(例如,postgres角色)进行连接,则可以连接到postgres或template1数据库.默认的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)
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)
通过提供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)
| 归档时间: |
|
| 查看次数: |
60416 次 |
| 最近记录: |