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

发布于 2024-08-14 06:26:23 字数 60 浏览 9 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

浮生未歇 2024-08-21 06:26:23

怎么样:

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

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
未蓝澄海的烟 2024-08-21 06:26:23

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

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_* 表中选择的优点是查询具有一定程度的可移植性。

I don't know the psycopg2 lib specifically, but the following query can be used to check for existence of a table:

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

The advantage of using information_schema over selecting directly from the pg_* tables is some degree of portability of the query.

彩扇题诗 2024-08-21 06:26:23
select exists(select relname from pg_class 
where relname = 'mytablename' and relkind='r');
select exists(select relname from pg_class 
where relname = 'mytablename' and relkind='r');
请止步禁区 2024-08-21 06:26:23

第一个答案对我不起作用。我发现成功检查了 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

The first answer did not work for me. I found success checking for the relation in 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
神爱温柔 2024-08-21 06:26:23
#!/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()
#!/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()
彩扇题诗 2024-08-21 06:26:23

我知道你要求 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 创建数据库连接对象 conn ,与此处的其他答案类似。

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.

有深☉意 2024-08-21 06:26:23

以下解决方案也处理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])

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])
秋日私语 2024-08-21 06:26:23

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

这是我想出的:

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

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')
£冰雨忧蓝° 2024-08-21 06:26:23

您可以查看 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() 将解析为 TrueFalse,因为EXISTS() 函数的。

You can look into pg_class catalog:

The catalog pg_class catalogs tables and most everything else that has
columns or is otherwise similar to a table. This includes indexes (but
see also pg_index), sequences (but see also pg_sequence), views,
materialized views, composite types, and TOAST tables; see relkind.
Below, when we mean all of these kinds of objects we speak of
“relations”. Not all columns are meaningful for all relation types.

Assuming an open connection with cur as cursor,

# 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() will resolve to either True or False because of the EXISTS() function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文