pythonpostgresqlpasswordsconnector

How do I connect to a postgresql database using python if the password contains "@" which is also a separator?


I'm trying to connect with no success to a postgresql database but the password containes "@" which is also a separator.

import pandas as pd
import connectorx as cx
import psycopg2

postgres_url = "postgresql://username:~2m4\9#T3(*4p**@**KL@aaa-aaaa.s111111111111.aws-emea.aaa.com:5432/bbb"

query = "select * from table1"

df = cx.read_sql(postgres_url, query)

df.head()

How can I overcome this? Thank you.


Solution

  • I found the solution:

    from urllib.parse import quote_plus

    password = "~2m4\9#T3(*4p@KL" encoded_password = quote_plus(password)

    postgres_url = "postgresql://username:" + encoded_password + "@aaa-aaaa.s111111111111.aws-emea.aaa.com:5432/bbb"

    query = "select * from table1"

    df = cx.read_sql(postgres_url, query)

    df.head()