psycopg2 的结果来自无效连接

psycopg2 has results from invalid connection

我正在使用 psycopg2 连接到我的本地 postgres 实例,但没有意识到我从未设置环境变量。我决定在 sys table (information_schema.tables) 上执行 select 以检查我是否已连接并返回结果。我很困惑很长一段时间试图弄清楚为什么我没有得到想要的结果。

幕后发生了什么导致了这种情况,为什么 psycopg2 不直接出错并说这是一个无效连接?

import psycopg2


conn = psycopg2.connect(
                host=None,
                port=None,
                dbname=None,
                user=None,
                password=None,
            )

cur = conn.cursor()

cur.execute("""SELECT table_name 
FROM information_schema.tables
limit 3 """)

print(cur.fetchall())

结果:

[('pg_statistic',), ('pg_foreign_table',), ('pg_authid',)]

当然,连接有效。当您像您所做的那样将空参数传递给 psycopg2.connect() 时,程序将获得 Postgres environment variables,这显然已正确设置。请注意,如果您将 DSN 字符串传递给函数,则情况并非如此:

conn = psycopg2.connect("host=None") # this defines an invalid connection

根据 the documentation:

The PostgreSQL documentation contains the complete list of the supported parameters. Also note that the same parameters can be passed to the client library using environment variables.