1

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

1 Answer 1

0

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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.