我有以下函数将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: '{'
1条答案
按热度按时间rdlzhqv91#
我需要逃离%