查询SQLite3时使用Python进行字符串格式化



我正在用Python中的SQlite3创建一个API应用程序。在我处理名称列中带有"的项目之前,一切都很好。条目将被写入数据库,但当我尝试使用以下内容从数据库中获取该项目时,代码将中断:

received_data = {"name": "Example with ' name", "price": 43,...}
new_item = cursor.execute("SELECT * FROM items WHERE name='{}'".format(received_data['name'])).fetchall()

我得到这个错误:

new_item = cursor.execute("SELECT * FROM items WHERE name='{}'".format(received_data['name'])).fetchall()
sqlite3.OperationalError: near "name": syntax error

既然我猜不到(我猜…(名字中可能使用的所有字符,那么最好的解决方案是什么?

根本不要使用format,这很危险。使用参数化查询:

new_item = cursor.execute("SELECT * FROM items WHERE name=?", (received_data['name'],)).fetchall()

最新更新