代码之家  ›  专栏  ›  技术社区  ›  Domnick

如何包含多个光标。在python中执行

  •  1
  • Domnick  · 技术社区  · 7 年前

    就像我必须从sql表中获取源、ID和目标一样,但它们存在于两个不同的表中,所以我尝试了

    dom_id=[1,10,19,31,37,42,48,57,63,64,65]
    
    for i in range(len(dom_id)):
      cursor.execute("SELECT xval, yval from table1 WHERE DOMID=?",dom_id[i])
      source=""
      for row in cursor.fetchall():
          source=float(row[0]),float(row[1])
          source=','.join(map(str, source))
      cursor.execute("select t1.id as pid,pxval,pyval from table2")
      ID=[]
      destination=""
      for row_d in cursor.fetchall():
            ID.append(row_d[0]) 
            destination = float(row_d[1]),float(row_d[2])
            destination = ','.join(map(str, destination))
    

    现在我正在使用 for循环 提取源和其他 for循环 提取 ID destination 我试过了

    cursor.execute(("SELECT xval, yval from table1 WHERE DOMID=?",dom_id[i]);("select t1.id as pid,pxval,pyval from table2 t1 left join (select * from table3 where clubid=?) t2 on t1.id=t2.pid where t1.cityid in (SELECT cityid FROM table1 WHERE domid = ? group by cityid) and t1.pxval>0 and t2.distance is null order by pid",(dom_id[i],dom_id[i])))
    

    但它会产生错误 SyntaxError: invalid syntax

    有什么办法可以把两者结合起来吗 cursor.execute 在单个for循环中。 有什么建议吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Bhushan Pant    7 年前

    我认为可以这样做:

    sqlQuery = "SELECT a.xval, a.yval,b.pid,pxval,b.pyval from table1 as a,
               (select t1.id as pid,pxval,pyval from <tbl1> t1 
               left join ( select * from <tbl2> where clubid="+clubid+") 
               t2 on t1.id=t2.projectid where t1.cityid in ( SELECT cityid 
               FROM <tbl3> WHERE cbdid ="+cbdid+" group by cityid) 
               and t1.pxval>0 and t2.distance is null order by projectid)
               as b WHERE a.DOMID="+dom_id[i]+"
    
    cursor.execute(sqlQuery)
    

    这将从两个表中提供所需的数据。

    注意:如果两个表的行数不同,则tell将为空值,您可以在代码中使用某些条件检查该值。

    如果要在单个执行中添加此选项,请尝试以下操作:

    cursor.execute("SELECT a.xval, a.yval,b.pid,b.pxval,b.pyval from table1 as a, (select t1.id as pid,pxval,pyval from table2 t1 left join (select * from table3 where clubid=?) t2 on t1.id=t2.pid where t1.cityid in (SELECT cityid FROM table1 WHERE domid = ? group by cityid) and t1.pxval>0 and t2.distance is null order by pid) as b WHERE a.DOMID=?",dom_id[i],dom_id[i],dom_id[i])
    

    希望这有帮助。