skip to Main Content

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, [email protected]*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 🙁

2

Answers


  1. Chosen as BEST ANSWER

    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, )


  2. Try this code to to handle the password having special characters in it.

    import psycopg2
    
    # Replace these values with your actual database credentials
    user = "your_username"
    password = "12@34\56.78*90"  # Note the double backslash to escape the backslash
    host = "your_host"
    dbname = "your_dbname"
    port = "your_port"
    
    # Escape the password and construct the connection string
    escaped_password = password.replace("'", "''")  # Replace single quotes with double single quotes
    connection_string = f"user={user} password='{escaped_password}' host={host} dbname={dbname} port={port}"
    
    # Establish the database connection
    connection = psycopg2.connect(connection_string)
    
    # Now you can use the 'connection' object to interact with the database
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search