簡體   English   中英

測試PostgreSQL表是否不存在(使用psycopg2)

[英]Test if PostgreSQL table does NOT exist (with psycopg2)

使用Psycopg2,我需要測試postgresql表是否存在。

在類似的問題中 ,建議使用以下測試:

cursor.execute("select exists(select * from myDb.mytable_%s)" % complementName)
tableExists = cursor.fetchone()[0]
print(tableExists)

如果表已經存在,則此方法很有效,並返回True ,但如果表存在則不起作用 我得到一個錯誤,而不是像我需要的那樣返回False

ProgrammingError:關系“myDb.mytable_001”不存在

我究竟做錯了什么? 如果表不存在,我該怎么做才能得到一個False語句? 謝謝你的幫助!

編輯

根據評論中的建議,我也試過:

tableExists = cursor.execute("SELECT 1 AS result FROM pg_database WHERE datname='mytable_001'")

tableExists = cursor.execute("SELECT EXISTS (SELECT 1 AS result FROM pg_tables WHERE schemaname = 'mySchema' AND tablename = 'mytable_001)')")

但兩者都只返回None ,無論表是否存在。 但是,我不確定語法,也許你可以指出我可能會犯的一些新手錯誤? 謝謝!

編輯2最后,解決方案包含上述后一個查詢的組合,並按如下方式獲取布爾結果:

cursor.execute("SELECT EXISTS (SELECT 1 AS result FROM pg_tables WHERE schemaname = 'mySchema' AND tablename = 'mytable_001');")
tableExists = cursor.fetchone()[0]

您可以從以下信息模式中獲取信息:

SELECT table_schema,table_name
FROM information_schema.tables
WHERE table_name like 'pg_database';

您的查詢似乎不正確。 你應該提供一個表名,你要驗證它是否存在......還有很多方法來驗證表是否存在,為什么要使它如此復雜.....

SELECT table_name FROM information_schema.tables where table_schema = 'your schema name '&store output in any variable然后驗證它是否為空......你應該沒事....

或使用

query = SELECT EXISTS (SELECT relname FROM pg_class WHERE relname = 'table 
name');
resp = cur.execute(query)
rows = cur.fetchone()
print(rows[0]) 

如果表存在則返回True,否則返回False ....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM