如何使用 Psycopg2 Python 库确定表是否存在?我想要一个真或假 bool 值。
最佳答案
怎么样:
>>> import psycopg2
>>> conn = psycopg2.connect("dbname='mydb' user='username' host='localhost' password='foobar'")
>>> cur = conn.cursor()
>>> cur.execute("select * from information_schema.tables where table_name=%s", ('mytable',))
>>> bool(cur.rowcount)
True
使用 EXISTS 的替代方法更好,因为它不需要检索所有行,而只需至少存在一个这样的行:
>>> cur.execute("select exists(select * from information_schema.tables where table_name=%s)", ('mytable',))
>>> cur.fetchone()[0]
True
关于python - 检查python下是否存在postgresql表(可能还有Psycopg2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1874113/