2016-05-23 317 views
0

這是我爲使用psycopg2連接Postgresql而編寫的代碼。我的psql和pgadminIII也在運行。連接拒絕Postgresql

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爲: 主機的所有所有0.0.0.0/0 MD5

再次,同樣的錯誤重複

回答

1

澄清

下面的答案被接受,但是,這不是問題的解決方案......問題在於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") 
+0

我試了兩次,但同樣的錯誤來了。 有什麼辦法讓服務器在本地主機上運行並建立TCP連接?我只是打開psql和pgadmin.Database使用psql創建gps_heatmap。 –

+0

值得一試。是的,你可以連接TCP。你是否檢查過postgres服務器運行的端口? (它默認爲5432)。你是否在使用psql時指定主機名(localhost)? (它可能使用unix域套接字)。什麼是成功連接的'psql'命令? – mhawke

+0

我明白了。實際上端口號有錯誤。它是5433,但代碼默認使用了5432 –

0

什麼工作對我來說是打開服務(搜索它在Windows),然後查找Postgres服務:PostgreSQL中,x64-10我的情況。

  1. 運行服務
  2. 重新啓動該服務

之後,錯誤不見了。起源

我的錯誤在PostgreSQL之後安裝MySQL,我想有一個在港口或東西的改變,但這個固定。