0

I have a function I'm trying to execute which calls in 4 different variables:

def listdbtables(dbname, user, host, password):
    try:
        conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" % dbname, % user, % host, % password)
        curs = conn.cursor()
        b = curs.execute("\l")
        print b
    except psycopg2.DatabaseError, ex:
        print "I am unable to connect the database: " + ex
        sys.exit(1)

I am unable to read in the variables with my current setup, how do I call in the variables properly in the conn variables.

Edit: Here is the error I am seeing:

      File "./pg_meta.py", line 35
    conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" (% dbname, % user, % host, % password))
                                                                             ^
SyntaxError: invalid syntax
0

3 Answers 3

2

try this:

def listdbtables(dbname, user, host, password):
    try:
        conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" % (dbname, user, host,password,))
        curs = conn.cursor()
        b = curs.execute("\l")
        print b
    except psycopg2.DatabaseError, ex:
        print "I am unable to connect the database: " + ex
        sys.exit(1)

the format portion needs to be a tuple for multiple values. you should also consider using String.format

Sign up to request clarification or add additional context in comments.

Comments

1

I think this is wrong syntax:

conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" % dbname, % user, % host, % password)

Change it to:

conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" %(dbname, user, host, password))

another way it to use .format():

conn = psycopg2.connect("dbname = {0} username = {1} host = {2} pass = {3}".format(dbname, user, host, password))

Comments

1

Your error is saying that you have incorrect syntax in your program. When using the % operator with multiple variables Python requires you to use parenthesis. Change your code to this instead:

conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" % (dbname, % user, % host, % password))

However, the recommend way to format variables into strings in newer Python versions would be to use the .format() method, instead of old style string formatting with %:

conn = psycopg2.connect("dbname = {} username = {} host = {} pass = {}".format(
    dbname,  user, host,  password)
)

Both methods have their advantageous and disadvantageous, so I encourage you to find which one works best for you. A good website to compare the two methods is pyformat.info.

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.