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

psycopg2连接本地PostgreSQL失败,TCP/IP连接被拒求助

免责声明:我已在互联网上查阅大量解决方案,但均无法解决我的问题

背景:我希望通过psycopg2将我的机器学习Python代码直接连接到PostgreSQL数据库管理系统。

connection = psycopg2.connect(
    dbname = '<databasename>', 
    user = 'postgres', 
    password = '<mypass>', 
    host = 'localhost',
    port = '5432',
    requiressl = 0
    )

cursor = connection.cursor()

错误信息:运行代码时出现如下错误

connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
    Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (::1), port 5432 failed: Cannot assign requested address
    Is the server running on that host and accepting TCP/IP connections?

看起来端口仅监听本地IP(127.0.0.1)。

已执行操作:

  • 根据网上资料,尝试修改postgresql.conf文件调整监听地址,允许外部访问。
  • 修改pg_hba.conf文件,将原配置:
    # IPv4 local connections:
    host    all             all             127.0.0.1/32         scram-sha-256
    
    修改为:
    # IPv4 local connections:
    host    all             all             0.0.0.0/0            scram-sha-256
    
  • 已重启机器,但问题仍未解决。
  • 确认端口正在监听正确的地址。

备注:上述两个文件的路径为\Program Files\PostgreSQL\16\data,使用Windows系统。

内容的提问来源于stack exchange,提问作者Fhlipfhlop

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 00:12:03