首页 > 解决方案 > 如何使用python连接到ec2上的postgresql数据库?

问题描述

这很可能是一个重复的问题,但我找不到对我有帮助的帖子。

我在 EC2 Linux 实例(不是 RDS 实例)上有一个 postgres 数据库。我可以从本地机器上的 putty 访问数据库(通过 SSH 连接到服务器,然后在同一个 shell 中连接到数据库,然后编写一个简单的 SQL),但无法从 python 访问。

这是我使用的python代码:

import pandas as pd
from sqlalchemy import create_engine

sql = """
SELECT *
FROM table1
"""
engine = create_engine("postgresql://my_user:my_pwd@public_ip_number/database_name")
df = pd.read_sql_query(sql, engine)

我已将入站实例的安全组上的入站规则定义为 在此处输入图像描述

出站规则为 在此处输入图像描述

这是我在本地机器上尝试使用 python 连接时遇到的错误

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused (0x0000274D/10061)
    Is the server running on host "my_public_ip" and accepting
    TCP/IP connections on port 5432?

编辑:

postgresql.conf我根据https://blog.bigbinary.com/2016/01/23/configure-postgresql-to-allow-remote-connection.html更改了文件

我所做的改变是: 在此处输入图像描述

我已经重新启动了 postgres 服务,现在当我尝试连接 python 时出现错误:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL:  no pg_hba.conf entry for host "24.1X.X.X", user "username", database "database", SSL off 

我不知道这个 IP 地址是什么(我在帖子中用 X 替换了真实地址)。

此错误会立即发生,而原始错误需要几秒钟才能发生。

标签: pythonpostgresqlamazon-ec2

解决方案


推荐阅读