【发布时间】:2019-10-28 06:41:13
【问题描述】:
我有一个包含许多列的 Pandas DataFrame,其中一列是包含 HTML 网页的“值”。我正在对 DataFrame 的每一行进行 Upsert 查询,但出现以下错误:
我已尝试使用以下方法转义 HTML:
df.value = df.value.apply(lambda x: re.escape(x))df.value = df.value.apply(lambda x: MySQLdb.escape_string(x))
这是我的功能:
non_key_cols = df.columns.tolist()
non_key_cols.remove(primary_key)
# df.value = df.value.apply(lambda x: re.escape(x))
df.value = df.value.apply(lambda x: MySQLdb.escape_string(x))
enclose_with_quote = [True if type_name.name=='object' else False for type_name in df.dtypes]
all_cols = df.columns.tolist()
#enclose df columns in inverted commas
for i in range(len(enclose_with_quote)):
if enclose_with_quote[i]:
df[all_cols[i]] = df[all_cols[i]].apply(lambda x: '"' + x + '"')
else:
df[all_cols[i]] = df[all_cols[i]].apply(lambda x: str(x))
sql = "INSERT INTO " \
+ tablename \
+ "(" + ", ".join([col for col in df.columns]) + ")" \
+ " VALUES " \
+ ", ".join(["(" + ", ".join(list(row)) + ")" for row in df.itertuples(index=False, name=None)]) \
+ " ON CONFLICT (" + primary_key + ") DO UPDATE SET " \
+ ", ".join([col + "=EXCLUDED." + col for col in non_key_cols])
conn = _getpostgres_connection()
cur = conn.cursor()
cur.execute(sql)
cur.close()
conn.commit()
conn.close()
这是我得到的错误:
ProgrammingError: syntax error at or near "margin" LINE 1:
...t_of_nums_not_in_table_regex) VALUES ("<p style=\"margin: 0p...
【问题讨论】:
-
这是postgresql还是mysql?在任何一种情况下,您都不应该连接自己的值,因为它非常不安全。使用参数化查询。
-
它是 Postgresql。我将研究参数化查询。虽然您知道如何转义 HTML 吗?使用 MySQLdb.escape_string(x),我能够为我的类似 MySQL 项目做事
-
不要自己转义 HTML。使用参数化查询,它应该为您处理转义。
标签: python pandas postgresql mysql-python