我是 python 的新手,我来自 PHP 的土地。我根据我的 PHP 知识在 python 中构建了一个这样的 SQL 查询,我收到了警告和错误
cursor_.execute("update posts set comment_count = comment_count + "+str(cursor_.rowcount)+" where ID = " + str(postid))
# rowcount here is int
形成查询的正确方法是什么?
此外,我如何转义字符串以形成 SQL 安全字符串?比如如果我想转义 -、'、"等,我曾经使用 addslashes。我们如何在 python 中做到这一点?
谢谢
最佳答案
首先,是时候学习使用 Matus 表达的方法安全地将变量传递给查询了。更清晰,
tuple = (foovar, barvar)
cursor.execute("QUERY WHERE foo = ? AND bar = ?", tuple)
如果你只需要传递一个变量,你仍然必须使它成为一个元组:在末尾插入逗号以告诉 Python 将其视为一个元组:tuple = (onevar,)
您的示例将采用以下形式:
cursor_.execute("update posts set comment_count = comment_count + ? where id = ?",
(cursor_.rowcount, postid))
您还可以像这样使用命名参数:
cursor_.execute("update posts set comment_count = comment_count + :count where id = :id",
{"count": cursor_.rowcount, "id": postid})
这次参数不是一个元组,而是一个由"key": value
成对组成的字典。
关于python - 在 python 中形成 MySQL 查询的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3948309/