1

绝对是这里的初学者。我在使用 postgres.app 和 sqlalchmey 连接到在 macosx 机器上本地运行的 postgresql 数据库时遇到问题:

导入 psycopg2 导入 sqlalchemy

engine = sqlalchemy.create_engine('postgresql://localhost/practice.db') engine.connect()

返回: OperationalError: (OperationalError) FATAL: 数据库“practice.db”不存在 无 无

谢谢,埃文

4

1 回答 1

0

您必须先创建该数据库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'
于 2013-07-23T19:56:53.107 回答