检查PostgreSQL下是否存在一个postgresql表(可能还有Psycopg2) [英] Checking if a postgresql table exists under python (and probably Psycopg2)

查看:164
本文介绍了检查PostgreSQL下是否存在一个postgresql表(可能还有Psycopg2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Psycopg2 Python库确定表是否存在?我想要一个真假布尔值。

How can I determine if a table exists using the Psycopg2 Python library? I want a true or false boolean.

推荐答案

怎么样:

>>> 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的替代方法更好,因为它不会不需要检索所有行,而仅要求存在至少一个这样的行:

An alternative using EXISTS is better in that it doesn't require that all rows be retrieved, but merely that at least one such row exists:

>>> cur.execute("select exists(select * from information_schema.tables where table_name=%s)", ('mytable',))
>>> cur.fetchone()[0]
True

这篇关于检查PostgreSQL下是否存在一个postgresql表(可能还有Psycopg2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆