简体   繁体   中英

Connecting to locally postgresql using sqlalchemy

Definitely a beginner here. I'm having issues connecting to postgresql database run locally on a macosx machine using postgres.app and sqlalchmey:

import psycopg2 import sqlalchemy

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

Returns: OperationalError: (OperationalError) FATAL: database "practice.db" does not exist None None

Thanks, Evan

You have to create that database before you can 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM