我是 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條件應該在表確實存在時執行。
uj5u.com熱心網友回復:
你應該試試這個。
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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/376796.html
標籤:Python sql PostgreSQL的 条件语句 存在
上一篇:計算串列中有多少項是相同的
