python - 查询 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()
推荐阅读
- r - 在多面散点图上使用 geom_blank 扩展比例
- python-2.7 - 如何为 python 2.7.9 下载 twilio 以发送文本
- rust - 如何使用参数实现 trait 默认实现
- java - 使用 Java 重新连接到进程
- static-libraries - Mingw64:添加静态链接库添加 libstdc++ 依赖项
- python - 如何最好地存储和调用在单个 XLSX 文件上运行的 pandas 脚本?
- python - python中属性装饰器对可变属性的用处
- node.js - 如何使用 Jest 库测试基本的 socket.io Node.js 应用程序?
- discord.js - 不和谐机器人有可能进入国外服务器吗?
- javascript - 为什么 React Context 只会触发从 DOM 元素向下传递的值函数