使用Psycopg2,我需要测试postgresql表是否存在。在
在类似的question中,建议使用以下测试:
cursor.execute("select exists(select * from myDb.mytable_%s)" % complementName)
tableExists = cursor.fetchone()[0]
print(tableExists)
如果表已经存在,那么这很有效,并返回True
,但如果表不存在,则不起作用。我没有像我需要的那样返回False
,而是得到了一个错误
ProgrammingError: relation "myDb.mytable_001" does not exist
我做错什么了?如果表不存在,我应该怎么做才能得到False
语句?谢谢你的帮助!在
编辑
根据评论中的建议,我也尝试了:
^{pr2}$以及
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_name FROM information_schema.tables where table_schema = 'your schema name
'将输出存储在任何变量中,然后验证它是否为空…您应该可以。。。。在或使用
如果表存在,则返回True,否则返回False。。。。在
相关问题 更多 >
编程相关推荐