Python 使用sqlalchemy连接到本地postgresql
绝对是个初学者。我在使用postgres.app和sqlalchmey连接到macosx计算机上本地运行的postgresql数据库时遇到问题: 导入psycopg2 进口炼金术 engine=sqlalchemy.create_引擎('postgresql://localhost/practice.db') 引擎连接() 返回: 操作错误:(操作错误)致命:数据库“practice.db”不存在 无无无 谢谢,Python 使用sqlalchemy连接到本地postgresql,python,sqlalchemy,postgresql-9.2,enthought,Python,Sqlalchemy,Postgresql 9.2,Enthought,绝对是个初学者。我在使用postgres.app和sqlalchmey连接到macosx计算机上本地运行的postgresql数据库时遇到问题: 导入psycopg2 进口炼金术 engine=sqlalchemy.create_引擎('postgresql://localhost/practice.db') 引擎连接() 返回: 操作错误:(操作错误)致命:数据库“practice.db”不存在 无无无 谢谢, Evan您必须先创建该数据库,然后才能创建引擎 from urlparse imp
Evan您必须先创建该数据库,然后才能创建引擎
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'