在cursor.execute()中的sql查询中传递多个参数

时间:2017-11-07 13:20:05

标签: python sql sql-server pyodbc

我试图将多个参数传递给sql查询,但它给我带来了错误,

这是查询

cbd_id=[1,10,19,31,37,42,48,57,63,64,65]


cursor.execute('''select t1.id as pid,pxval,pyval from <tbl1> t1 left join (select * from <tbl2> where clubid=? t2 on t1.id=t2.projectid where t1.cityid in (SELECT cityid FROM <tbl3> WHERE cbdid =? group by cityid) and t1.pxval>0 and t2.distance is null order by projectid)''',(cbd_id[i],cbd_id[i]))

它给我错误

ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 't2'. (102) (SQLExecDirectW)")

但是我检查过无法确定问题,

对此有任何建议都会有所帮助。

由于

1 个答案:

答案 0 :(得分:1)

如错误消息所示,您的SQL命令文本格式错误。为清晰起见,重新格式化了您的查询

select t1.id as pid,pxval,pyval 
from 
    <tbl1> t1 
    left join 
    (
        select * 
        from <tbl2> 
        where clubid=? 
    t2 
        on t1.id=t2.projectid 
where 
    t1.cityid in (
            SELECT cityid 
            FROM <tbl3> 
            WHERE cbdid =? 
            group by cityid) 
    and 
    t1.pxval>0 
    and 
    t2.distance is null 
order by projectid)

请注意,<tbl2>子查询没有右括号。您的查询可能应该是

select t1.id as pid,pxval,pyval 
from 
    <tbl1> t1 
    left join 
    (
        select * 
        from <tbl2> 
        where clubid=? 
    ) t2 
        on t1.id=t2.projectid 
where 
    t1.cityid in (
            SELECT cityid 
            FROM <tbl3> 
            WHERE cbdid =? 
            group by cityid) 
    and 
    t1.pxval>0 
    and 
    t2.distance is null 
order by projectid