Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用sqlalchemy连接到本地postgresql_Python_Sqlalchemy_Postgresql 9.2_Enthought - Fatal编程技术网

Python 使用sqlalchemy连接到本地postgresql

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

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

导入psycopg2 进口炼金术

engine=sqlalchemy.create_引擎('postgresql://localhost/practice.db') 引擎连接()

返回: 操作错误:(操作错误)致命:数据库“practice.db”不存在 无无无

谢谢,
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'