无法使用psycopg2从Google colab连接到Postgres服务器

时间:2020-06-24 12:39:51

标签: python postgresql google-colaboratory psycopg2

我在尝试从google colab连接到postgres时总是遇到错误,但是在pycharm上,这些相同的代码很容易连接到服务器。这是代码:

import psycopg2

params = {
    "host"      : "localhost",
    "database"  : "somedb",
    "user"      : "postgres",
    "password"  : "mypassword"
}
def connect(params):
    """ Connect to the PostgreSQL database server """
    conn = None
    try:
        # connect to the PostgreSQL server
        print('Connecting to the PostgreSQL database...')
        conn = psycopg2.connect(**params)
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
         
    return conn

connect(params)

我遇到的错误

OperationalError: could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?
could not connect to server: Cannot assign requested address
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?

1 个答案:

答案 0 :(得分:0)

确保在您的 PostgreSQL 服务器中允许的 IP 地址列表中包含: 34.0.0.0/8 和 35.0.0.0/8 是 Google Colab 的地址。