python, accessing a psycopg2 form a def?

Posted by i-Malignus on Stack Overflow See other posts from Stack Overflow or by i-Malignus
Published on 2010-03-24T19:19:45Z Indexed on 2010/03/24 19:23 UTC
Read the original article Hit count: 415

Filed under:
|

i'm trying to make a group of defs in one file so then i just can import them whenever i want to make a script in python

i have tried this:

def get_dblink( dbstring):
"""
Return a database cnx.
"""
global psycopg2 
try
    cnx = psycopg2.connect( dbstring)
except Exception, e:
    print "Unable to connect to DB. Error [%s]" % ( e,)
    exit( )

but i get this error: global name 'psycopg2' is not defined

in my main file script.py

i have:

import psycopg2, psycopg2.extras
from misc_defs import * 

hostname = '192.168.10.36'
database = 'test'
username = 'test'
password = 'test'

dbstring = "host='%s' dbname='%s' user='%s' password='%s'" % ( hostname, database, username, password)

cnx = get_dblink( dbstring)

can anyone give me a hand?

© Stack Overflow or respective owner

Related posts about python

Related posts about psycopg2