Search code examples
pythonpostgresqlpsycopg2

Psycopg2: how to deal with special characters in password?


I am trying to connect to a db instance, but my password has the following special characters: backslash, plus, dot, asterisk/star and at symbol. For example, 12@34\56.78*90 (regex nightmare lol)

How do I safe pass it to the connection string? My code looks like that:

connection_string = f'user={user} password={pass} host={host} dbname={dbname} port={port}'

connection = psg2.connect(connection_string)

It gives me wrong pass/username error. However, I tried this combination directly on the db and it works, and I tried another combination on the python code and it worked as well. So looks like the problem is the password being passed weirdly to the connection.

I tried urllib scape, I tried double quotes on the password, nothing works so far :(


Solution

  • Based on a reddit thread, I found out that passing variable by variable directly instead of a connection string did the trick:

    con = psycopg2.connect( dbname=dn, user=du, password=dp, host=dh, port=dbp, )