postgresql PythonPostgres-psycopg 2插入到列中包含花括号的表中

tzcvj98z  于 2023-04-05  发布在  PostgreSQL
关注(0)|答案(1)|浏览(101)

我有以下函数将dataframe插入postgres表:

def insert(conn, df, table, return_field_list):
        tuples = [tuple(x) for x in df.to_numpy()]
        cols = ','.join(list(df.columns))
        query  = "INSERT INTO {} ({}) VALUES (%%s)".format(table, cols)
        sub_stmt = ' RETURNING {} '.format(' ,'.join(return_field_list))
        query += sub_stmt
        cursor = conn.cursor()
        try:
            extras.execute_values(cursor, query, tuples)
            conn.commit()
            return cursor.fetchall()
        except (Exception, psycopg2.DatabaseError) as error:
            print("Error: %s" % error)
            conn.rollback()
            cursor.close()
            return None
        finally:
            if cursor is not None:
                cursor.close()

我的一些表列包含特殊字符,例如“Ni[%{wt}]”,S[%{wt}]在将其传递给上面的函数之前,我用双引号“转义”了dataframe列(除了id和name列):

df.rename(columns = lambda col: f'"{col}"' if col not in ('id', 'name') else col, inplace=True)

但是,该函数返回以下错误:

Error: unsupported format character: '{'
rdlzhqv9

rdlzhqv91#

我需要逃离%

r ={}
for c in df.columns:
  r = c
  if '%' in r:
    r = r.replace('%', '%%')
    replace[c] = r
df.rename(columns = replace, inplace=True)

相关问题