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

Hel*_*nar 46 python postgresql psycopg2

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

Pet*_*sen 71

怎么样:

>>> 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
Run Code Online (Sandbox Code Playgroud)

使用EXISTS的替代方案更好,因为它不需要检索所有行,而只需要存在至少一个这样的行:

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

  • 关闭但更好地使用`exists()`.:) (2认同)
  • 我补充说,但为什么它"更好"? (2认同)
  • @Peter它更好,因为它只需要找到匹配`where`条件的第一行,而`rowcount`必须检索所有行. (2认同)

ove*_*ink 20

我具体不知道psycopg2 lib,但可以使用以下查询来检查表是否存在:

SELECT EXISTS(SELECT 1 FROM information_schema.tables 
              WHERE table_catalog='DB_NAME' AND 
                    table_schema='public' AND 
                    table_name='TABLE_NAME');
Run Code Online (Sandbox Code Playgroud)

使用information_schema而不是直接从pg_*表中进行选择的优点是查询的某种程度的可移植性.


Chr*_*heD 5

select exists(select relname from pg_class 
where relname = 'mytablename' and relkind='r');
Run Code Online (Sandbox Code Playgroud)


小智 5

第一个答案对我不起作用。我发现成功检查了 pg_class 中的关系:

def table_exists(con, table_str):
    exists = False
    try:
        cur = con.cursor()
        cur.execute("select exists(select relname from pg_class where relname='" + table_str + "')")
        exists = cur.fetchone()[0]
        print exists
        cur.close()
    except psycopg2.Error as e:
        print e
    return exists
Run Code Online (Sandbox Code Playgroud)