首页 > 解决方案 > 查询 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

什么是最好的解决方案,因为我无法猜测(我猜......)某人可能在名称中使用的所有字符?

标签: pythonstringsqlite

解决方案


千万不要用format这个,很危险。使用参数化查询:

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

推荐阅读