如何确定是否存在一个表使用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)", ('mytable',))
>>> cur.fetchone()[0]
True

其他提示

我不知道psycopg2 LIB具体地,但下面的查询可被用来检查一个表中的存在:

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

使用INFORMATION_SCHEMA过直接从PG_ *表中选择的优点是一定程度的所述查询的便携性。

select exists(select relname from pg_class 
where relname = 'mytablename' and relkind='r');
#!/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()

第一个答案并没有为我工作。我发现对于在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

下面的溶液处理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])

扩展在上述使用EXISTS的,我需要的东西一般测试表的存在。我发现,测试使用取上一个SELECT语句结果产生的空白现有的表结果“无” - 不理想

这就是我想出了:

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')
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top