如何处理PostgreSQL密码中包含@符号的连接问题
解决PostgreSQL连接URL中密码含@符号的问题
当密码里包含@这类特殊字符时,直接拼接URL会导致解析错误,这里有两种靠谱的解决办法:
方法1:对密码进行URL编码
URL里的特殊字符需要转义,@对应的URL编码是%40,你可以手动替换或者用Python的urllib.parse.quote_plus自动处理:
from urllib.parse import quote_plus username = "你的用户名" password = "Test@123" hostname = "你的主机名" port_id = "5432" database = "你的数据库名" # 对密码进行URL编码 encoded_password = quote_plus(password) url = f"postgresql://{username}:{encoded_password}@{hostname}:{port_id}/{database}" # 此时URL会变成 postgresql://用户名:Test%40123@主机名:5432/数据库名
方法2:使用SQLAlchemy的参数式构造(更推荐)
不用手动拼接URL,直接给create_engine传入参数字典,完全避免URL解析问题:
from sqlalchemy import create_engine db_params = { "username": "你的用户名", "password": "Test@123", "host": "你的主机名", "port": "5432", "database": "你的数据库名" } engine = create_engine( "postgresql://", connect_args=db_params )
或者用URL对象构建,兼容性更好:
from sqlalchemy.engine import URL url_object = URL.create( "postgresql", username=username, password=password, host=hostname, port=port_id, database=database ) engine = create_engine(url_object)
这两种方法都能正确识别密码里的@符号,不用修改密码就能正常连接数据库。
内容的提问来源于stack exchange,提问作者jen
相关产品推荐
相关产品推荐

