【问题标题】:Connecting to locally postgresql using sqlalchemy使用 sqlalchemy 连接到本地 postgresql
【发布时间】:2013-07-23 19:33:25
【问题描述】:
这里绝对是初学者。我在使用 postgres.app 和 sqlalchmey 连接到在 macosx 机器上本地运行的 postgresql 数据库时遇到问题:
导入 psycopg2
导入 sqlalchemy
engine = sqlalchemy.create_engine('postgresql://localhost/practice.db')
engine.connect()
返回:
OperationalError: (OperationalError) FATAL: 数据库“practice.db”不存在
无 无
谢谢,
埃文
【问题讨论】:
标签:
python
sqlalchemy
postgresql-9.2
enthought
【解决方案1】:
您必须先创建该数据库,然后才能create_engine
from urlparse import urlparse, urlunparse
def recreate_db(url):
parsed = urlparse(url)
#parse url so you know host
host_url = urlunparse((parsed.scheme, parsed.netloc, '/', '', '', ''))
#create_engine without database name
engine = create_engine(host_url, convert_unicode=True)
dbname = parsed.path.strip('/')
engine.execute('commit')
try:
#drop (and clean) database if it exists with raw query
engine.execute('drop database `%s`;'%dbname)
engine.execute('commit')
except OperationalError:
pass
#create database
engine.execute('create database `%s` default character set utf8 ;'%dbname)
engine.execute('commit')
print 'Done cleanup'