gpt4 book ai didi

python - 如何使用python连接postgres

转载 作者:行者123 更新时间:2023-11-29 13:47:28 25 4
gpt4 key购买 nike

我尝试通过以下代码使用 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 x.x.x.x/32 md5

关于python - 如何使用python连接postgres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46035167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com