Python& SQL通过pyodbc - 通过循环使用动态where子句执行查询

时间:2017-10-18 13:49:12

标签: python sql pyodbc

我试图生成&通过pyodbc执行SQL语句。我期待多个SQL语句,所有这些语句都以相同的SELECT& FROM但在WHERE中具有不同的值。我的WHERE子句中的值来自循环表 - SQL脚本在表中找到的每个不同的值,我需要Python生成另一个带有此值的SQL语句作为WHERE子句。

我几乎就是这样,我只是努力让pyodbc将我的查询字符串放入SQL喜欢的格式中。到目前为止我的代码:

import pyodbc

cn = pyodbc.connect(connection info)

cursor = cn.cursor()

result = cursor.execute('SELECT distinct searchterm_name FROM table1')

for row in result:
    sql = str("SELECT * from table2 WHERE table1.searchterm_name = {c}".format(c=row)),

#print sql

此代码生成这样的输出,其中"在此处命名"基于table1中的值。

('SELECT * from ifb_person WHERE searchterm_name = (u\'name here\', )',)

我只需要删除查询周围的所有垃圾& where子句所以它看起来像这样。然后我可以将它传递给另一个cursor.execute()

来自ifb_person的SELECT * WHERE searchterm_name ='在这里命名'

修改

for row in result:
    cursor.execute("insert into test (searchterm_name) SELECT searchterm_name FROM ifb_person WHERE searchterm_name = ?",
               (row[0],))

此查询失败,错误为pyodbc.ProgrammingError: No results. Previous SQL was not a query.

基本上我要做的是让Python为table1中找到的每个结果生成一个新的SQL语句。第二个查询是针对表ifb_person运行搜索并将结果插入表" test"。我想为table1

中的每个结果运行单独的SQL语句

1 个答案:

答案 0 :(得分:2)

pyodbc允许我们遍历Cursor对象以返回行,在此期间Cursor对象仍在使用"因此我们不能使用相同的Cursor对象来执行其他操作。例如,此代码将失败:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <div id="color-cont">
      <h3>Choose the theme color for your profile</h3>
      <div id="colorPicker">
        <div class="color-circle"></div>
        <div class="color-circle"></div>
        <div class="color-circle"></div>
        <div class="color-circle"></div>
        <div class="color-circle"></div>
        <div class="color-circle"></div>
        <div class="color-circle"></div>
        <div class="color-circle"></div>
        <div class="color-circle"></div>
      </div>
    </div>

我们可以使用crsr = cnxn.cursor() result = crsr.execute("SELECT ...") # result is just a reference to the crsr object for row in result: # we are actually iterating over the crsr object crsr.execute("INSERT ...") # this clobbers the previous crsr object ... # ... so the next iteration of the for loop fails with " Previous SQL was not a query." 将所有行检索到fetchall() ...

来解决这个问题。
result

...或在循环中使用不同的Cursor对象

result = crsr.execute("SELECT ...").fetchall()  
# result is now a list of pyodbc.Row objects and the crsr object is no longer "in use"