gpt4 book ai didi

python - 使用executemany从pandas数据帧更新mysql数据库

转载 作者:行者123 更新时间:2023-11-29 10:42:22 24 4
gpt4 key购买 nike

我正在使用 mysqldb 尝试更新数据库中的大量记录。

cur.executemany("""UPDATE {} set {} =%s Where id = %s """.format(table, ' = %s, '.join(col)),updates.values.tolist())

我收到错误消息...

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near...

因此,我尝试输出实际的 sql 更新语句,因为使用以下代码该错误消息没有帮助:

cur.execute('set profiling = 1')
try:

cur.executemany("""UPDATE {} set {} =%s Where id = %s """.format(table, ' = %s, '.join(col)),updates.values.tolist())
except Exception:
cur.execute('show profiles')
for row in cur:
print(row)

该 print 语句似乎将 update 语句截断为 300 个字符。我在文档中找不到任何有关限制的内容,所以我想知道这是 print 语句限制还是 mysqldb?

有没有办法可以仅使用 python 而不是 mysqldb 生成更新语句来查看完整的语句?

最佳答案

要准确查看光标正在执行的内容,您可以使用 cursor.statement 命令,如下所示 here在 API 中。这可能有助于调试。

我没有使用 mySQL 适配器的经验,但我每天都会使用 PostgreSQL 适配器。至少在这种情况下,建议不要直接格式化查询字符串,而是让 cursor.execute 语句中的第二个参数进行替换。这可以避免带引号的字符串等问题。这是一个例子,第二个是正确的(至少对于 Postgres 来说):

cur.execute("""UPDATE mytbl SET mycol = %s WHERE mycol2 = %s""".format(val, cond))

cur.execute("""UPDATE mytbl SET mycol = %(myval)s WHERE mycol2 = %(mycond)s""", {'myval': val, 'mycond': cond})

这可能会导致查询

UPDATE mytbl SET mycol = abc WHERE mycol2 = xyz

而不是

UPDATE mytbl SET mycol = 'abc' WHERE mycol2 = 'xyz'.

如果您自己在查询中进行值替换,则需要显式添加这些引号,这会变得烦人并绕过数据库适配器的类型处理(请记住,这只是一个文本示例)。 See the API有关此表示法和 cursor.executemany 命令的更多信息。

关于python - 使用executemany从pandas数据帧更新mysql数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45240759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com