简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM