0

I'm trying to connect to a postgres database by using psycopg2. I ask for the user and user password via input. But I think, this way doesnt let me connect to the database. Is there another way to place the values?

I try to connect like this:

connection = psycopg2.connect("host=localhost dbname=dbname user=%s password=%s", (username, password)) 

This is the error I get:

    connection = _connect(dsn, connection_factory=connection_factory, **kwasync)
TypeError: 'tuple' object is not callable 
1
  • Do you want to use %-replacement? In that case you are just missing a % sign where you placed a comma between your template-string and the tuple. Commented May 9, 2022 at 15:44

1 Answer 1

1

There are a couple of ways to build the connection string from inputs, first:

# From input
user_name = 'some_name'
pwd = 'some_pwd'

connection = psycopg2.connect(host=localhost, dbname=dbname, user=user_name, password=pwd)

Second from here Make dsn:

from psycopg2.extensions import make_dsn
dsn = make_dsn('host=localhost dbname=dbname', user=user_name, password=pwd)
connection = psycopg2.connect(dsn)

UPDATE, forgot the most obvious way:

dsn = 'host=localhost dbname=dbname user=' + user_name + ' password='  + pwd
connection = psycopg2.connect(dsn)
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.