python - 检查python下是否存在postgresql表(可能还有Psycopg2)

标签 python postgresql psycopg2

如何使用 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/

相关文章:

python - Psycopg2 "copy_from"命令,可以忽略引号中的定界符(出现错误)?

python-3.x - psycopg2 不将数据保存到 postgres 数据库中

python - pip install myclient 错误 - 在 Windows 7 上使用 Python 3.7.0

python - 使用 numpy vectorize 时如何避免大量额外的内存消耗?

sql - 通过自定义比较器在 Housenumber 列上排序 Postgresql 查询结果

linux - 为什么行元组在 Postgres 中是不可变的

python - 类型错误 : 'psycopg2._psycopg.Binary' object does not support indexing

python matplotlib : unable to call FuncAnimation from inside a function

python - 按月份名称和年份对 groupby pandas 输出进​​行排序

python - Django如何合并查询结果