Checking if a postgresql table exists under python (and probably Psycopg2)

前端 未结 8 1999
我在风中等你
我在风中等你 2020-12-08 18:24

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

相关标签:
8条回答
  • 2020-12-08 18:58

    Expanding on the above use of EXISTS, I needed something to test table existence generally. I found that testing for results using fetch on a select statement yielded the result "None" on an empty existing table -- not ideal.

    Here's what I came up with:

    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')
    
    0 讨论(0)
  • 2020-12-08 18:59

    How about:

    >>> 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
    

    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
    
    0 讨论(0)
  • 2020-12-08 18:59

    I know you asked for psycopg2 answers, but I thought I'd add a utility function based on pandas (which uses psycopg2 under the hood), just because pd.read_sql_query() makes things so convenient, e.g. avoiding creating/closing cursors.

    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))
    

    I still use psycopg2 to create the db-connection object conn similarly to the other answers here.

    0 讨论(0)
  • 2020-12-08 19:03
    #!/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()
    
    0 讨论(0)
  • 2020-12-08 19:06
    select exists(select relname from pg_class 
    where relname = 'mytablename' and relkind='r');
    
    0 讨论(0)
  • 2020-12-08 19:14

    The following solution is handling the schema too:

    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])
    
    0 讨论(0)
提交回复
热议问题