繁体   English   中英

如何使用python连接Postgres

[英]How to connect postgres using python

我尝试通过以下img代码使用python连接postgres。 但是我无法连接它,我遇到了一些错误。

import psycopg2
import sys

def main():
    #Define our connection string
    conn_string = "host='11.20.89.233' dbname='postgres' user='good_user' password='secret'"

    # print the connection string we will use to connect
    print "Connecting to database\n ->%s" % (conn_string)

    # get a connection, if a connect cannot be made an exception will be raised here
    conn = psycopg2.connect(conn_string)

    # conn.cursor will return a cursor object, you can use this cursor to perform queries
    cursor = conn.cursor()
    print "Connected!\n"

if __name__ == "__main__":
    main()

我收到以下错误。

grtmgr@BLR1000005591:~/mppcases> python testcon.py
Connecting to database
        ->host='11.20.89.233' dbname='good_user' user='secret' 
password='mpp_tool'
Traceback (most recent call last):
  File "testcon.py", line 19, in <module>
    main()
  File "testcon.py", line 12, in main
     conn = psycopg2.connect(conn_string)
  File "/usr/lib64/python2.6/site-packages/psycopg2/__init__.py", line 179, 
in connect
    connection_factory=connection_factory, async=async)
psycopg2.OperationalError: could not connect to server: Connection refused
        Is the server running on host "11.20.89.233" and accepting
       TCP/IP connections on port 16100?

首先,您需要确保使用正确的端口,其次,需要将IP地址添加到PostgreSQL pg_hba.conf文件。

host all all xxxx/32 md5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM