检查一个postgresql表是否存在于python(可能是Psycopg2)
发布时间:2020-12-13 16:44:38 所属栏目:百科 来源:网络整理
导读:如何使用Psycopg2 Python库确定表是否存在?我想要一个真或假布尔。 怎么样: import psycopg2 conn = psycopg2.connect("dbname='mydb' user='username' host='localhost' password='foobar'") cur = conn.cursor() cur.execute("select * from information
如何使用Psycopg2 Python库确定表是否存在?我想要一个真或假布尔。
怎么样:
>>> 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)",)) >>> cur.fetchone()[0] True (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |