如何使用 SQLAlchemy 创建一个新数据库? [英] How to create a new database using SQLAlchemy?

查看:80
本文介绍了如何使用 SQLAlchemy 创建一个新数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 SQLAlchemy,可以像这样创建一个 Engine 对象:

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

如果create_engine 的参数中指定的数据库(在本例中为mydb)不存在,

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

解决方案

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

<预><代码>>>>engine = sqlalchemy.create_engine("postgres://postgres@/postgres")

您不能使用 engine.execute() 但是,因为 postgres 不允许您在事务中创建数据库,并且 sqlalchemy 总是尝试在事务中运行查询.要解决此问题,请从引擎获取底层连接:

<预><代码>>>>conn = engine.connect()

但连接仍将在事务内,因此您必须使用 commit 结束打开的事务:

<预><代码>>>>conn.execute("提交")

然后您可以继续使用正确的 PostgreSQL 命令为其创建数据库.

<预><代码>>>>conn.execute("创建数据库测试")>>>conn.close()

Using SQLAlchemy, an Engine object is created like this:

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

Accessing engine fails if the database specified in the argument to create_engine (in this case, mydb) does not exist. Is it possible to tell SQLAlchemy to create a new database if the specified database doesn't exist?

解决方案

On postgres, three databases are normally present by default. If you are able to connect as a superuser (eg, the postgres role), then you can connect to the postgres or template1 databases. The default pg_hba.conf permits only the unix user named postgres to use the postgres role, so the simplest thing is to just become that user. At any rate, create an engine as usual with a user that has the permissions to create a database:

>>> engine = sqlalchemy.create_engine("postgres://postgres@/postgres")

You cannot use engine.execute() however, because postgres does not allow you to create databases inside transactions, and sqlalchemy always tries to run queries in a transaction. To get around this, get the underlying connection from the engine:

>>> conn = engine.connect()

But the connection will still be inside a transaction, so you have to end the open transaction with a commit:

>>> conn.execute("commit")

And you can then proceed to create the database using the proper PostgreSQL command for it.

>>> conn.execute("create database test")
>>> conn.close()

这篇关于如何使用 SQLAlchemy 创建一个新数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆