隨着SQLAlchemy中,發動機產生這樣的:如何使用SQLAlchemy創建新的數據庫?
from sqlalchemy import create_engine
engine = create_engine("postgresql://localhost/mydb")
訪問如果數據庫不存在engine
失敗。如果指定的數據庫不存在,是否可以告訴SQLAlchemy創建新的數據庫?
隨着SQLAlchemy中,發動機產生這樣的:如何使用SQLAlchemy創建新的數據庫?
from sqlalchemy import create_engine
engine = create_engine("postgresql://localhost/mydb")
訪問如果數據庫不存在engine
失敗。如果指定的數據庫不存在,是否可以告訴SQLAlchemy創建新的數據庫?
在postgres上,默認情況下通常存在三個數據庫。如果您能夠以超級用戶身份進行連接(例如,postgres
角色),則可以連接到postgres
或template1
數據庫。默認的pg_hba.conf只允許名爲postgres
的unix用戶使用postgres
角色,所以最簡單的事情就是成爲該用戶。無論如何,創建一個引擎像往常一樣具有權限來創建一個數據庫中的用戶:
>>> engine = sqlalchemy.create_engine("postgres://[email protected]/postgres")
不能使用engine.execute()
然而,因爲Postgres沒有允許你創建內部交易數據庫,SQLAlchemy的總是試圖在事務中運行查詢。爲了解決這個問題,得到來自發動機的基礎連接:
>>> conn = engine.connect()
但連接仍將是一個交易裏面,所以你要結束開放交易與commit
:
>>> conn.execute("commit")
而且您可以繼續使用適當的PostgreSQL命令創建數據庫。
>>> conn.execute("create database test")
>>> conn.close()
這是可能的,以避免手動事務管理,同時通過提供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')
此外,如果你不知道該數據庫不存在是有辦法忽略數據庫通過抑制sqlalchemy.exc.ProgrammingError
例外由於存在創建錯誤:
import contextlib
import sqlalchemy.exc
with contextlib.suppress(sqlalchemy.exc.ProgrammingError):
# creating database as above
看來你不能連接到progres服務器而沒有指定數據庫,所以你可能想連接到默認的「postgres」數據庫來執行db創建命令,否則它會嘗試連接到默認的「用戶「數據庫,如果它不存在則投訴。 – Acorn
見http://sqlalchemy-utils.readthedocs.org/en/latest/database_helpers.html
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))
創建一個新的數據庫或只是表?我還沒有遇到過許多實際創建數據庫的ORM。 –
我確實發現[this](http://www.mail-archive.com/[email protected]/msg05520.html) –
有幫助的:http://sqlalchemy-utils.readthedocs.org/en/latest/database_helpers .html –