如何检查我在 Python 中连接的 Postgres 数据库中是否存在列?

How to check the existence of a column in the Postgres database I am connected to in Python?

我在 Python 中使用 postgres 和库 psycopg2。连接到数据库后,我试图检查是否存在具有给定名称的 table。在 postgres 中,我使用以下行来执行此操作:

\connect myDB
select exists(select * from pg_tables where schemaname='public' AND tablename='mytable';)

如果 table 存在但不存在时也有效。 在 python 中,我使用以下行执行此操作:

import psycopg2 as pg
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT;
from psycopg2 import sql;

conn = pg.connect(user='postgres', host='localhost', password="pwd");
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT);
conn.autocommit = True
sql_table_check = sql.SQL("select exists(select * from pg_tables where schemaname='public' AND tablename={});")\
        .format(sql.Identifier("mytable"));
cur = conn.cursor()

但这返回了错误

psycopg2.errors.UndefinedColumn: column "mytable" does not exist
LINE 1: ...m pg_tables where schemaname='public' AND tablename="mytable");

因为这样的table还没有创建。

检查 psycopg2 中是否存在列的正确方法是什么?

编辑

请注意,我想检查 table 在我连接的数据库中是否存在,我不介意它是否存在于另一个数据库中。

因此您可以通过使用 tryexcept 继续

来克服错误
sql_table_check = sql.SQL("select exists(select * from pg_tables where schemaname='public' AND tablename={});")\
        .format(sql.Identifier("mytable"));
try:
    cur = conn.cursor()
    print('Table exists')
except:
    print('Table does not exist')

根据评论编辑

您也可以通过

捕获错误以便稍后检查
sql_table_check = sql.SQL("select exists(select * from pg_tables where schemaname='public' AND tablename={});")\
        .format(sql.Identifier("mytable"));
try:
    cur = conn.cursor()
    print('Table exists')
except Exception as e:
    print(e)
    print('Table does not exist')

例如,简单地说,如果我们尝试:

try:
    a = 5 / 0
except Exception as e:
    print(e)

我们将得到输出

division by zero

可以通过调试e异常部分的内容得到准确的格式字符串

所以我们可以使用它来识别错误,再次使用,如:

try:
    a = a / 0
except Exception as e:
    print(e)
    if e.args[0] == 'division by zero':
        print('it is division by zero Error')
    else:
        raise(e)

因此,如果错误不是预期的错误,则会引发另一个错误。

您可能会从 psycopg2 文档中得到错误异常,就像 https://docs.python.org/3/library/exceptions.html

中的 python 一样

如以下代码所示:

try:
    a = 5 / 0
except ZeroDivisionError:
    print('it is division by zero Error')

所以我们得到:

it is division by zero Error

但是当我们遇到另一个错误时:

try:
    a = 5 / 0
except ZeroDivisionError:
    print('it is division by zero Error')

我们得到另一个错误

NameError: name 'b' is not defined

我的评论作为回答:

import psycopg2

con = psycopg2.connect("dbname=production host=localhost user=postgres")
tbl_sql = "SELECT count(*) FROM pg_tables WHERE schemaname='public' AND tablename= %s"
cur = con.cursor()
cur.execute(tbl_sql, ('cell_per',))
cur.fetchone()
(1,)

cur.execute(tbl_sql, ('cell_p',))
cur.fetchone()
(0,)