PostgreSQL 连接被拒绝

5

这是我使用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

再次运行,出现相同错误。

3个回答

4

澄清

以下答案已被采纳,但并非该问题的解决方案...问题在于postgresql服务器配置为端口5433,而不是默认端口5432。应该使用以下方法来解决问题:

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

Translated answer

尝试将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")

我尝试了两种方法,但是出现了相同的错误。 有没有办法在本地主机上运行服务器并建立TCP连接?我只是打开了psql和pgadmin。使用psql创建了数据库gps_heatmap。 - Himal Acharya
值得一试。是的,您可以使用TCP连接。您是否检查了Postgres服务器运行的端口?(默认为5432)。在使用psql时,您是否指定了主机名(localhost)?(它可能正在使用Unix域套接字)。成功连接的“psql”命令是什么? - mhawke
我明白了。实际上端口号有误。它应该是5433,但代码默认使用了5432。 - Himal Acharya

0

对我有效的方法是打开服务(在Windows中搜索),然后查找postgres服务:在我的情况下是postgresql-x64-10。

  1. 运行服务
  2. 重新启动服务

之后,错误就消失了。

我的错误是在安装PostgreSQL后安装MySQL引起的,我猜可能是端口或其他方面发生了变化,但这个方法解决了问题。


0

我把我的IDE改成了Atom或使用PyCharm,然后就没有错误了,你也可以检查一下端口。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接