简体   繁体   English

测试PostgreSQL表是否不存在(使用psycopg2)

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

Using Psycopg2, I need to test whether a postgresql table exists or not. 使用Psycopg2,我需要测试postgresql表是否存在。

In a similar question , it is recommended to use the following test: 在类似的问题中 ,建议使用以下测试:

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

This works great if the table already exists, and returns True , but it does not work if the table does not exist. 如果表已经存在,则此方法很有效,并返回True ,但如果表存在则不起作用 Instead of returning False like I would need, I get an error 我得到一个错误,而不是像我需要的那样返回False

ProgrammingError: relation "myDb.mytable_001" does not exist ProgrammingError:关系“myDb.mytable_001”不存在

What am I doing wrong? 我究竟做错了什么? What should I do in order to get a False statement if the table doesn't exist? 如果表不存在,我该怎么做才能得到一个False语句? Thanks for any help! 谢谢你的帮助!

EDIT 编辑

Following advice in comments, I tried also: 根据评论中的建议,我也试过:

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

and

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

But both simply return None , whether the table exists or not. 但两者都只返回None ,无论表是否存在。 However, I'm not sure of the syntax, maybe you can point out some novice mistake I may be making? 但是,我不确定语法,也许你可以指出我可能会犯的一些新手错误? Thanks! 谢谢!

EDIT 2 Finally the solution consisted in a combination of the latter query above, and fetching the boolean result as follows: 编辑2最后,解决方案包含上述后一个查询的组合,并按如下方式获取布尔结果:

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

You can get info from information schema like: 您可以从以下信息模式中获取信息:

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

Your query does not seem to right. 您的查询似乎不正确。 You are supposed to provide table name for which you are verifying whether it is exist or not...... There are many more ways to verify whether table exist or not why to make it so complex..... 你应该提供一个表名,你要验证它是否存在......还有很多方法来验证表是否存在,为什么要使它如此复杂.....

SELECT table_name FROM information_schema.tables where table_schema = 'your schema name ' & store output in any variable then verify whether it is empty or not...you should be fine.... SELECT table_name FROM information_schema.tables where table_schema = 'your schema name '&store output in any variable然后验证它是否为空......你应该没事....

or use 或使用

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

this will return True if table exist otherwise False.... 如果表存在则返回True,否则返回False ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM