如何检查表中是否存在列,如果不存在则不插入列

Cel*_*tas 2 python postgresql psycopg2

我试图让一个程序在尝试将一个值插入一个不存在的列时不会崩溃(这首先发生的原因是因为它插入的列名来自另一个的值为红色可能包含拼写错误的表格.

如果列不存在,我该如何跳过INSERT

for row in cur2:
            if row[1] > specialLimit:
               try:
                 cur.execute("INSERT INTO {}.{} (item_id) VALUES ('{}')".format(schema, table, row[0]))
                 con.commit()
               except psycopg2.DatabaseError as e:
                 print('Error: '+e)
Run Code Online (Sandbox Code Playgroud)

这仍然给出错误:

LINE 1: INSERT INTO load_primary.item_properties (exotic) VALUES (...

Vor*_*Vor 7

您可以在发出请求之前运行简单查询:

select exists (
  select 1 from information_schema.columns 
  where table_name ='my_table' 
  and column_name='my_column'
);
Run Code Online (Sandbox Code Playgroud)

这将返回布尔值并psycopg2自动将其转换为python的布尔值.

另一种方法是运行单个查询以立即检查所有列.并仅将数据插入到存在的数据中.这可能稍微高效一点.