Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将变量传递给mysql查询?_Python_Apache_Python 2.7_Mod Wsgi_Wsgi - Fatal编程技术网

Python 如何将变量传递给mysql查询?

Python 如何将变量传递给mysql查询?,python,apache,python-2.7,mod-wsgi,wsgi,Python,Apache,Python 2.7,Mod Wsgi,Wsgi,这个没有错误 cursor.execute ("update `1` set `2`='aaa' where `1`='5'") 这个有错误 cursor.execute ("update `1` set `2`=aaa where `1`='5'") 区别在于,我试图将变量“aaa”传递给它 这是apache的错误日志 [2013年5月14日星期二21:20:24][error][client 127.0.0.1] 操作错误:(1054,“字段列表”中的未知列“aaa”) 在PHP中,我只

这个没有错误

cursor.execute ("update `1` set `2`='aaa' where `1`='5'")
这个有错误

cursor.execute ("update `1` set `2`=aaa where `1`='5'")
区别在于,我试图将变量“aaa”传递给它

这是apache的错误日志

[2013年5月14日星期二21:20:24][error][client 127.0.0.1] 操作错误:(1054,“字段列表”中的未知列“aaa”)


在PHP中,我只需在mysql查询中键入
$aaa
,因此在python中,我只需键入
aaa

如果您试图传递变量的值,则需要在字符串外部写入“aaa”。因此,不是:

cursor.execute ("update `1` set `2`=aaa where `1`='5'")
尝试:

请注意,如果使用python,可能需要使用以下命令将变量转换为字符串(例如,如果它包含一个数字):


在php中,您可以执行
execute(“更新'1'集'2'=$aaa,其中'1'='5'”)
但您应该执行
execute(“更新'1'集'2'=?其中'1'='5'”,$aaa)
。但您至少应该执行
execute(“更新'1'集'2'=”。mysql\u real\u escape\u string($aaa)。“其中'1'='5'”)


在Python中,您使用
execute(“更新'1'集'2'=%s其中'1'='5'”[aaa])

不,不要这样做-现在您已经打开了SQL注入的大门,就像在PHP中一样。阅读@Daniel的答案。顺便说一句,Python DB API支持预先准备好的语句,所有驱动程序(包括MySQL驱动程序)也支持预先准备好的语句,所以不要推荐第二部分。有关更多信息,请参见Python wiki中的和条目。我编辑了你的问题以反映这一点,顺便提一下+1。
cursor.execute ("update `1` set `2`= '" + aaa + "' where `1`='5'")
str(aaa)