如何检查我在Python中连接到的Postgres数据库中的列是否存在?
我在 Python 中将 postgres 与库一起使用psycopg2。连接到数据库后,我试图检查是否存在具有给定名称的表。在 postgres 中,我使用以下几行来执行此操作:
connect myDB
select exists(select * from pg_tables where schemaname='public' AND tablename='mytable';)
如果表存在,则此方法有效,但如果不存在,则此方法有效。在 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");
因为还没有创建这样的表。
检查 psycopg2 中是否存在列的正确方法是什么?
编辑
请注意,我想检查我连接的数据库中是否存在该表,我不介意它是否存在于另一个数据库中。
回答
我的评论作为答案:
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,)