Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use psycopg2 connection string with variables?

I am trying to connect to a Postgres Database with variables like this:

cs = "dbname=%s user=%s password=%s host=%s port=%s",(dn,du,dp,dh,dbp)
con = None
con = psycopg2.connect(cs)

However I get the error message:

TypeError: argument 1 must be string, not tuple

I need to be able to use variables in the connection string. Anyone know how to accomplish this?

like image 358
Laurence Avatar asked Aug 20 '15 13:08

Laurence


People also ask

Is psycopg2 connection thread safe?

Thread and process safetyThe Psycopg module and the connection objects are thread-safe: many threads can access the same database either using separate sessions and creating a connection per thread or using the same connection and creating separate cursors. In DB API 2.0 parlance, Psycopg is level 2 thread safe.

Can psycopg2 connect to MySQL?

Both MySQL and PostgreSQL are supported. You would use psycopg2 to connect to Postgres and e.g. MySQLdb to connect to MySQL. You also have to change the connection string.

What is the host in psycopg2 connect?

In your context of psycopg2 and PostgreSQL connection, the host normally means the IP address of the PostgreSQL server or the resolvable name of the PostgreSQL server such as DNS name if it has.


1 Answers

Your code currently creates a tuple with your string and the tuple you are trying to sub. You need:

cs = "dbname=%s user=%s password=%s host=%s port=%s" % (dn,du,dp,dh,dbp)
like image 69
rp372 Avatar answered Oct 05 '22 17:10

rp372