59

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

4

9 回答 9

97

怎么样:

>>> 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
于 2009-12-09T14:28:57.087 回答
23

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

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

与直接从 pg_* 表中选择相比,使用 information_schema 的优势在于查询的某种程度的可移植性。

于 2009-12-09T14:09:52.143 回答
5
select exists(select relname from pg_class 
where relname = 'mytablename' and relkind='r');
于 2009-12-09T14:08:06.157 回答
3

第一个答案对我不起作用。我发现成功检查了 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
于 2014-01-31T16:52:55.030 回答
2
#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys


con = None

try:

    con = psycopg2.connect(database='testdb', user='janbodnar') 
    cur = con.cursor()
    cur.execute('SELECT 1 from mytable')          
    ver = cur.fetchone()
    print ver    //здесь наш код при успехе


except psycopg2.DatabaseError, e:
    print 'Error %s' % e    
    sys.exit(1)


finally:

    if con:
        con.close()
于 2015-06-18T03:50:25.423 回答
2

我知道你要求 psycopg2 的答案,但我想我会添加一个基于 pandas 的实用程序函数(它在后台使用 psycopg2),只是因为pd.read_sql_query()让事情变得如此方便,例如避免创建/关闭游标。

import pandas as pd

def db_table_exists(conn, tablename):
    # thanks to Peter Hansen's answer for this sql
    sql = f"select * from information_schema.tables where table_name='{tablename}'" 
    
    # return results of sql query from conn as a pandas dataframe
    results_df = pd.read_sql_query(sql, conn)

    # True if we got any results back, False if we didn't
    return bool(len(results_df))

我仍然使用 psycopg2 来创建 db-connection 对象conn,类似于此处的其他答案。

于 2020-07-20T04:03:26.823 回答
0

以下解决方案schema也在处理:

import psycopg2

with psycopg2.connect("dbname='dbname' user='user' host='host' port='port' password='password'") as conn:
    cur = conn.cursor()
    query = "select to_regclass(%s)"
    cur.execute(query, ['{}.{}'.format('schema', 'table')])

exists = bool(cur.fetchone()[0])
于 2018-03-08T09:54:02.877 回答
0

扩展 EXISTS 的上述使用,我需要一些东西来测试表的存在性。我发现在 select 语句上使用 fetch 测试结果会在现有的空表上产生结果“无”——不理想。

这是我想出的:

import psycopg2

def exist_test(tabletotest):

    schema=tabletotest.split('.')[0]
    table=tabletotest.split('.')[1]
    existtest="SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = '"+schema+"' AND table_name = '"+table+"' );"

    print('existtest',existtest)

    cur.execute(existtest) # assumes youve already got your connection and cursor established

    # print('exists',cur.fetchall()[0])
    return ur.fetchall()[0] # returns true/false depending on whether table exists


exist_test('someschema.sometable')
于 2019-04-26T19:32:48.630 回答
0

您可以查看pg_class目录:

目录 pg_class 对表和大多数其他具有列或与表类似的东西进行编目。这包括索引(另见 pg_index)、序列(另见 pg_sequence)、视图、物化视图、复合类型和 TOAST 表;见relkind。下面,当我们指的是所有这些类型的对象时,我们所说的“关系”。并非所有列对所有关系类型都有意义。

cur假设作为光标打开连接,

# python 3.6+
table = 'mytable'
cur.execute(f"SELECT EXISTS(SELECT relname FROM pg_class WHERE relname = {table});")

if cur.fetchone()[0]:
    # if table exists, do something here
    return True

cur.fetchone()将解析为True或者False因为EXISTS()函数。

于 2021-08-21T07:14:58.437 回答