防止python中的SQL注入 [英] Protecting against SQL injection in python
问题描述
我在 Python 中有一些代码可以在 sqlite 数据库中设置 char(80) 值.
I have some code in Python that sets a char(80) value in an sqlite DB.
该字符串是通过文本输入字段直接从用户那里获取的,并通过 JSON 结构中的 POST 方法发送回服务器.
The string is obtained directly from the user through a text input field and sent back to the server with a POST method in a JSON structure.
在服务器端,我目前将字符串传递给调用 SQL UPDATE 操作的方法.
On the server side I currently pass the string to a method calling the SQL UPDATE operation.
它有效,但我知道它根本不安全.
It works, but I'm aware it is not safe at all.
无论如何,我希望客户端是不安全的,因此任何保护都将放在服务器端.我可以做些什么来保护 UPDATE 操作免受 SQL 注入的影响?
I expect that the client side is unsafe anyway, so any protection is to be put on the server side. What can I do to secure the UPDATE operation agains SQL injection ?
一个可以引用"文本以便它不会混淆 SQL 解析器的函数是我正在寻找的.我希望存在这样的功能,但找不到.
A function that would "quote" the text so that it can't confuse the SQL parser is what I'm looking for. I expect such function exist but couldn't find it.
这是我当前设置字符字段名称标签的代码:
Here is my current code setting the char field name label:
def setLabel( self, userId, refId, label ):
self._db.cursor().execute( """
UPDATE items SET label = ? WHERE userId IS ? AND refId IS ?""", ( label, userId, refId) )
self._db.commit()
推荐答案
来自文档:
con.execute("insert into person(firstname) values (?)", ("Joe",))
这转义了"Joe"
,所以你想要的是
This escapes "Joe"
, so what you want is
con.execute("insert into person(firstname) values (?)", (firstname_from_client,))
这篇关于防止python中的SQL注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!