拒绝连接到 Postgresql

新手上路,请多包涵

这是我为使用 psycopg2 连接 Postgresql 编写的代码。我的 psql 和 pgadminIII 也在运行。

 import psycopg2

connection = psycopg2.connect(dbname="gps_heatmap",user="postgres",host="localhost",password="1234")
cursor = connection.cursor()

cursor.execute("DROP TABLE IF EXISTS roads")
cursor.execute("CREATE TABLE roads (" +
                   "id SERIAL PRIMARY KEY," +
                   "name VARCHAR," +
                   "centerline GEOMETRY)")
cursor.execute("CREATE INDEX ON roads USING GIST(centerline)")

connection.commit()

但是出现以下错误:

  OperationalError                          Traceback (most recent call last)
    <ipython-input-14-03e3f214b83e> in <module>()
          1 import psycopg2
          2
    ----> 3 connection = psycopg2.connect(dbname="gps_heatmap",user="postgres",host="localhost",password="1234",port="5432")
          4 cursor = connection.cursor()
          5

C:\Users\*******\Anaconda3\lib\site-packages\psycopg2__init__.py in connect(dsn, database, user, password, host, port, connection_factory, cursor_factory, async, **kwargs)
    162                 for (k, v) in items])
    163
--> 164     conn = _connect(dsn, connection_factory=connection_factory, async=async)
    165     if cursor_factory is not None:
    166         conn.cursor_factory = cursor_factory

OperationalError: could not connect to server: Connection refused (0x0000274D/10061)
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?
could not connect to server: Connection refused (0x0000274D/10061)
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?

我将 pg_hbf.conf 编辑为:host all all 0.0.0.0/0 md5

再次,同样的错误重复

原文由 Himal Acharya 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 490
2 个回答

澄清

下面的答案被接受,但是,这不是问题的解决方案……问题是 postgresql 服务器配置为端口 5433,而不是默认端口 5432。这应该可以解决问题:

 connection = psycopg2.connect(database="gps_heatmap", user="postgres", password="1234", host="localhost", port=5433)


原答案

尝试将 dbname="gps_heatmap" 替换为 database="gps_heatmap" 因为前者用于连接字符串,而后者在关键字参数传递给 psycopg2.connect() 时使用:

 connection = psycopg2.connect(database="gps_heatmap", user="postgres", host="localhost", password="1234")

或者您可以使用连接字符串:

 connection = psycopg2.connect("dbname=gps_heatmap user=postgres host=localhost password=1234")

原文由 mhawke 发布,翻译遵循 CC BY-SA 3.0 许可协议

将我的 IDE 更改为 Atom 或使用 pycharm 并且不再有错误你也可以检查端口

原文由 rutto 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题