python - Connecting to locally postgresql using sqlalchemy -
definitely beginner here. i'm having issues connecting postgresql database run locally on macosx machine using postgres.app , sqlalchmey:
import psycopg2 import sqlalchemy
engine = sqlalchemy.create_engine('postgresql://localhost/practice.db') engine.connect()
returns: operationalerror: (operationalerror) fatal: database "practice.db" not exist none none
thanks, evan
you have create database before can create_engine
from urlparse import urlparse, urlunparse def recreate_db(url): parsed = urlparse(url) #parse url 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 exists 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'
Comments
Post a Comment