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

updating a mysql database from a pandas dataframe wiht executemany

我正在使用 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)

那个打印语句似乎在 300 个字符处截断了更新语句。我在文档中找不到任何关于限制的内容,所以我想知道这是打印语句限制还是我的sqldb?

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

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

我没有使用 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 命令的更多信息。