通过JDBC驱动连接多地址PostgreSQL数据库失败求助
PostgreSQL JDBC连接字符串报错问题
我可以通过psql使用以下连接字符串正常连接PostgreSQL:
psql 'postgresql://clienthttpfile@pg-clienthttpfile-dev3.dev-dc1-c1.gb.app:5432,pg-clienthttpfile-dev3.dev-dc2-c1.gb.app:5432/clienthttpfile?connect_timeout=5&target_session_attrs=read-write'
但尝试通过JDBC驱动连接应用时,该连接字符串无法正常工作。我尝试了带双引号和单引号的配置:
database.url="jdbc:postgresql://clienthttpfile@pg-clienthttpfile-dev3.dev-dc1-c1.gb.app:5432,pg-clienthttpfile-dev3.dev-dc2-c1.gb.app:5432/clienthttpfile?connect_timeout=5&target_session_attrs=read-write" database.url='jdbc:postgresql://clienthttpfile@pg-clienthttpfile-dev3.dev-dc1-c1.gb.app:5432,pg-clienthttpfile-dev3.dev-dc2-c1.gb.app:5432/clienthttpfile?connect_timeout=5&target_session_attrs=read-write'
两种方式均报错:
Driver org.postgresql.Driver claims to not accept jdbcUrl,
若不使用引号,连接则直接超时。请问问题出在哪里?
问题原因及解决方案
问题出在三个核心点,对应解决方案如下:
1. 配置文件中的引号错误
properties格式的配置文件中,配置值不需要添加引号。你添加的双引号/单引号会被当作JDBC URL的一部分,导致驱动识别的URL以引号开头,不符合jdbc:postgresql://的标准前缀格式,直接触发“不接受该URL”的报错。
2. &符号未转义导致参数截断
在properties文件中,&是配置项的分隔符。你未转义的&target_session_attrs=read-write会被解析成新的配置项,导致实际传递给JDBC的URL缺失该参数,进而引发连接超时。
3. 多主机场景下的用户名传递兼容性问题
将用户名放在@前缀跟随多主机的写法,部分JDBC驱动版本可能存在解析歧义,建议改用URL参数user=clienthttpfile传递用户名,提升兼容性。
正确配置示例
若使用properties配置文件:
database.url=jdbc:postgresql://pg-clienthttpfile-dev3.dev-dc1-c1.gb.app:5432,pg-clienthttpfile-dev3.dev-dc2-c1.gb.app:5432/clienthttpfile?user=clienthttpfile&connect_timeout=5&target_session_attrs=read-write
若使用YAML配置文件:
database: url: "jdbc:postgresql://pg-clienthttpfile-dev3.dev-dc1-c1.gb.app:5432,pg-clienthttpfile-dev3.dev-dc2-c1.gb.app:5432/clienthttpfile?user=clienthttpfile&connect_timeout=5&target_session_attrs=read-write"
内容的提问来源于stack exchange,提问作者user3016959
相关产品推荐
相关产品推荐

