SQL 查询的形成问题。 Python, pymysql

The problem with the formation of SQL queries. Python, pymysql

我想把bot数据库从SQLite改成MySQL(pymysql)和运行成问题

我有一个生成 sql 查询的函数,但由于某种原因它停止工作了:

def update_format_with_args(sql, parameters: dict):
values = ", ".join([
    f"{item} = ?" for item in parameters
])
sql = sql.replace("XXX", values)
return sql, tuple(parameters.values())

def update_settingsx(**kwargs):
with connection.cursor() as db:
    sql = f"UPDATE main_settings SET XXX "
    sql, parameters = update_format_with_args(sql, kwargs)
    db.execute(sql, parameters)
    db.commit()

错误:

 update_settingsx(profit_buy=now_unix)
   File "/root/rent/bot_id/utils/db_api/sqlite.py", line 154, in update_settingsx
     db.execute(sql, parameters)
   File "/usr/local/lib/python3.7/dist-packages/pymysql/cursors.py", line 168, in execute
     query = self.mogrify(query, args)
   File "/usr/local/lib/python3.7/dist-packages/pymysql/cursors.py", line 147, in mogrify
     query = query % self._escape_args(args, conn)
 TypeError: not all arguments converted during string formatting

并非每个数据库连接器都支持 ? 替换方案。 Pymysql 使用 %s 代替。

另一种选择是使用命名替换:

def update_format_with_args(sql, parameters: dict):
    values = ", ".join([
        f"{item} = %({item})s" for item in parameters
    ])
    sql = sql.replace("XXX", values)
    return sql, parameters