You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 21:51:23