在查询中插入python变量

2024-06-28 20:22:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从mysql中收回一个相当复杂的查询-我已经让连接正常工作,并且可以在硬编码值时成功地完成查询。在

我想将其中一个值设为python变量-我遵循我在这里找到的方法:How to use variables in SQL statement in Python?,因为列出的用例与我的非常相似。在

我使用的mysql execute函数与解决的问题不同,我无法确定将python变量放入execute调用的位置。在

我的代码:

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链接起来。在

固定

好了,开始工作了:

^{pr2}$

以及

 targetPUID = "x-fmt/409"

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


Tags: nameinexecuteifascountmysqlsig
3条回答
cur.execute(..., (targetPUID,))

尝试:

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),)) 

好了,开始工作了:

 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)

以及

^{pr2}$

相关问题 更多 >