Home > Software engineering >  How can I connect to postgres data base by input parameters?
How can I connect to postgres data base by input parameters?

Time:05-10

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 

CodePudding user response:

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)
  • Related