【问题标题】:PostgreSQL Table exists but python says it doesn'tPostgreSQL 表存在,但 python 说它不存在
【发布时间】:2022-01-13 17:45:37
【问题描述】:

我是 Python 新手,虽然这似乎是一些愚蠢的错误,但我无法弄清楚我做错了什么。任何建议或提示都会非常有帮助。如果这个问题之前已经回答过,请给我链接。

我正在编写一个简单的 python 脚本,它将连接到数据库。现在在该数据库中,我正在检查 test_run 表是否存在。如果存在,则打印它存在,如果不存在,则创建表。

# Connect to the Database Server, now with the created DB
try:
    connection = psycopg2.connect(user="postgres", password="postgres", host="127.0.0.1", port="5432",
                                  database="dashboard")
except (Exception, psycopg2.Error) as error:
    print("Connection not established", error)


# Check if test_run Table Exists
cursor = connection.cursor()
if bool(cursor.execute("SELECT EXISTS(SELECT * FROM information_schema.tables WHERE table_name='test_run')")):
    print('test_run table exists. Moving On.')
else:
    print('test_run does not exist. Creating the Table now.')
    cursor.execute("CREATE TABLE test_run (run_id serial PRIMARY KEY, date date, status varchar(255), "
                   "total_time integer, project_name varchar(255));")

现在数据库中存在test_run 表,当我运行SELECT EXISTS 命令时,我得到一个true

现在,当我运行上述脚本时,else 条件被执行,表明test_run 表不存在。但理想情况下,应该在表确实存在时执行if 条件。

【问题讨论】:

    标签: python sql postgresql conditional-statements exists


    【解决方案1】:

    你应该试试这个。

    import psycopg2
    # Connect to the Database Server, now with the created DB
    try:
        connection = psycopg2.connect(user="postgres", password="postgres", host="127.0.0.1", port="5432", database="dashboard")
    except (Exception, psycopg2.Error) as error:
        print("Connection not established", error)
    
    
    # Check if test_run Table Exists
    cursor = connection.cursor()
    cursor.execute("SELECT EXISTS(SELECT * FROM information_schema.tables WHERE table_name='test_run')")
    if bool(cursor.fetchone()[0]):
        print('test_run table exists. Moving On.')
    else:
        print('test_run does not exist. Creating the Table now.')
        cursor.execute("CREATE TABLE test_run (run_id serial PRIMARY KEY, date date, status varchar(255), "
                   "total_time integer, project_name varchar(255));")
        connection.commit()
    

    【讨论】:

    • cursor.fetchone()[0] 成功了。非常感谢您的快速帮助。
    猜你喜欢
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    相关资源
    最近更新 更多