将python变量插入查询中

时间:2012-02-27 05:12:21

标签: python mysql variables

我正在尝试从mysql中撤回一个相当复杂的查询 - 我已经使连接工作正常,并且在我对值进行硬编码时可以成功完成查询。

我想将其中一个值设为python变量 - 我遵循我在此处找到的方法:How to use variables in SQL statement in Python?因为列出的用例看起来与我的几乎相同。

我使用的mysql执行函数与解决的问题不同,我无法弄清楚将python变量放在执行调用中的位置。

我的代码:

targetPUID = "fmt/123"

cur.execute("""
(
SELECT `PUID`,`DROID_V`,`SIG_V`,`SPEED`,
COUNT(distinct IF(sourcelist.hasExtension=1,NAME,NULL)) as Ext,
COUNT(distinct IF(sourcelist.hasExtension=0,NAME,NULL)) as NoExt,
COUNT(distinct NAME) as `All`
FROM sourcelist, main_small
WHERE sourcelist.SourcePUID ="%s" AND main_small.NAME = sourcelist.SourceFileName
GROUP BY `PUID`,`DROID_V`,`SIG_V`,`SPEED` ORDER BY `DROID_V` ASC, `SIG_V`
 )
""") 

我知道我需要对我的变量targetPUID添加引用,以便与查询中的%s相关联。

___________________ FIXED ___________________

好的,让它运转起来:

 cur.execute("""
 (
 SELECT `PUID`,`DROID_V`,`SIG_V`,`SPEED`,
 COUNT(distinct IF(sourcelist.hasExtension=1,NAME,NULL)) as Ext,
 COUNT(distinct IF(sourcelist.hasExtension=0,NAME,NULL)) as NoExt,
 COUNT(distinct NAME) as `All`
 FROM sourcelist, main_small
 WHERE sourcelist.SourcePUID =%s AND main_small.NAME = sourcelist.SourceFileName
 GROUP BY `PUID`,`DROID_V`,`SIG_V`,`SPEED` ORDER BY `DROID_V` ASC, `SIG_V`
 )
""",targetPUID)

 targetPUID = "x-fmt/409"

我还没有足够的代表添加修复程序。谢谢阅读。

3 个答案:

答案 0 :(得分:2)

尝试:

cur.execute("""
(
SELECT `PUID`,`DROID_V`,`SIG_V`,`SPEED`,
COUNT(distinct IF(sourcelist.hasExtension=1,NAME,NULL)) as Ext,
COUNT(distinct IF(sourcelist.hasExtension=0,NAME,NULL)) as NoExt,
COUNT(distinct NAME) as `All`
FROM sourcelist, main_small
WHERE sourcelist.SourcePUID = %s AND main_small.NAME = sourcelist.SourceFileName
GROUP BY `PUID`,`DROID_V`,`SIG_V`,`SPEED` ORDER BY `DROID_V` ASC, `SIG_V`
 )
""",(int(targetPUID),)) 

答案 1 :(得分:1)

cur.execute(..., (targetPUID,))

答案 2 :(得分:1)

好的,让它运转起来:

 cur.execute("""
 (
 SELECT `PUID`,`DROID_V`,`SIG_V`,`SPEED`,
 COUNT(distinct IF(sourcelist.hasExtension=1,NAME,NULL)) as Ext,
 COUNT(distinct IF(sourcelist.hasExtension=0,NAME,NULL)) as NoExt,
 COUNT(distinct NAME) as `All`
 FROM sourcelist, main_small
 WHERE sourcelist.SourcePUID =%s AND main_small.NAME = sourcelist.SourceFileName
 GROUP BY `PUID`,`DROID_V`,`SIG_V`,`SPEED` ORDER BY `DROID_V` ASC, `SIG_V`
 )
""",targetPUID)

targetPUID = "x-fmt/409"