Search code examples
pythonmysqlpymysql

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


I want to change the bot database from SQLite to MySQL (pymysql) and ran into a problem.

I have a function for generating sql queries, but for some reason it stopped working:

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()

Error:

 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

Solution

  • Not every database connector supports the ? substitution scheme. Pymysql uses %s instead.

    Another alternative would be to use named substition:

    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