Python script and database connection.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rohankudtarkar
    New Member
    • Apr 2008
    • 1

    Python script and database connection.

    Hi,
    I wrote a Python scripts, i need to connect this with my database in postgresql, but while running the __init__.py it gives the message that unable to connect to database. Please guide me. my code is as follow...
    try:
    conn=psycopg2.c onnect("dbname= "+ dbname + "user=" + username + "password=" + password)
    print"connected "
    except:
    print "I am unable to connect to the database, exiting."
    sys.exit()
  • jlm699
    Contributor
    • Jul 2007
    • 314

    #2
    Originally posted by rohankudtarkar
    Hi,
    I wrote a Python scripts, i need to connect this with my database in postgresql, but while running the __init__.py it gives the message that unable to connect to database. Please guide me. my code is as follow...
    try:
    conn=psycopg2.c onnect("dbname= "+ dbname + "user=" + username + "password=" + password)
    print"connected "
    except:
    print "I am unable to connect to the database, exiting."
    sys.exit()
    On first inspection it looks like you are missing spaces between your string concatenation so that inside the connect function you are passing the following:
    "dbname=foobaru ser=usrfoopassw ord=passwd".
    I find it easier to make the string first so that you can do some sanity-checking and then passing the string to the connect function. Here's a snippet from a postgresql gui that I made:
    [code=python]dsn = "host=" + dbip + " dbname=" + dbname +\
    " user=" + dbuser + " password=" + dbpass
    #Defaults: ip=192.168.100. 48 dbname=Tools user=toolsusr password=toolsd b"
    try:
    db = psycopg2.connec t(dsn)
    except:
    #WriteToLogs('C annot connect to Database, please check your Database Options')
    return
    [/code]Notice the spaces before dbname=, user=, and password= .... HTH

    Comment

    Working...