在python中形成MySQL查询的正确方法是什么?

时间:2010-10-16 09:20:06

标签: python sql mysql

我是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中做到这一点?

由于

2 个答案:

答案 0 :(得分:3)

首先,现在是学习使用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的字典。

答案 1 :(得分:2)

来自python手册:

t = (symbol,)

c.execute( 'select * from stocks where symbol=?', t )

这样可以防止SQL注入(假设这是您引用的SQL安全)并且还解决了格式化问题

相关问题