我正在尝试连接到数据库实例,但我的密码包含以下特殊字符:反斜杠、加号、点、星号/星号和 at 符号。例如,[email protected]*90(正则表达式噩梦哈哈)
如何安全地将其传递到连接字符串?我的代码看起来像这样:
connection_string = f'user={user} password={pass} host={host} dbname={dbname} port={port}'
connection = psg2.connect(connection_string)
它给了我错误的通行证/用户名错误。然而,我直接在数据库上尝试了这个组合,它工作正常,我在 python 代码上尝试了另一个组合,它也工作正常。所以看起来问题是密码被奇怪地传递到连接。
我尝试了 urllib scape,我在密码上尝试了双引号,到目前为止没有任何效果:(
尝试使用此代码来处理包含特殊字符的密码。
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