测试 Postgres-DB 的连接

Testing the connection of Postgres-DB

如果软件连接到特定的 Postgre-DB,我想在 GUI 上放一个按钮。我写了一个小的测试函数:如果它可以连接到数据库,它 returns 正确,如果不能,它 returns 错误。

代码有效,但有一个问题:如果没有连接(我只是拔掉网线,没有其他变化),它只是 需要太多时间。 如果没有连接,你能帮我使代码更快吗?

这是我的简单测试函数:

import psycopg2

def postgres_test():

    try:
        conn = psycopg2.connect("dbname='mydb' user='myuser' host='my_ip' password='mypassword'")
        conn.close()
        return True
    except:
        return False

感谢您的评论。是的,它与超时有关。

这是我更快的代码:

import psycopg2

def postgres_test():

    try:
        conn = psycopg2.connect("dbname='mydb' user='myuser' host='my_ip' password='mypassword' connect_timeout=1 ")
        conn.close()
        return True
    except:
        return False

要测试与 python 的 postgres 连接,首先您必须安装此软件包:

pip install psycopg2-binary

并尝试此代码:

import psycopg2

conn = psycopg2.connect(dbname="db_name",
                        user="user_name",
                        host="127.0.0.1",
                        password="******",
                        port="5432")
cursor = conn.cursor()
cursor.execute('SELECT * FROM information_schema.tables')
rows = cursor.fetchall()
for table in rows:
    print(table)
conn.close()