Python&SQL via pyodbc使用动态where claus通过循环执行查询

2024-05-17 19:45:22 发布

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

我试图通过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

这段代码生成这样一个输出,其中“name here”基于表1中的值。在

^{pr2}$

我只需要删除所有关于query&where子句的废话,使其看起来像这样。然后我可以把它传给另一个光标.执行()

从ifb_person中选择*,其中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为它在表1中找到的每个结果生成一个新的SQL语句。第二个查询是对表ifb_person运行搜索,并将结果插入表“test”。我想对表1中找到的每个结果运行单独的SQL语句


Tags: namefromsql语句resultcnwhereselect
1条回答
网友
1楼 · 发布于 2024-05-17 19:45:22

pyodbc允许我们迭代一个Cursor对象以返回行,在此期间,Cursor对象仍然处于“使用中”,因此我们不能使用同一个Cursor对象来执行其他操作。例如,此代码将失败:

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中的所有行来解决这个问题。。。在

^{pr2}$

。。。或者在循环中使用不同的游标对象

crsr_select = cnxn.cursor()
crsr_insert = cnxn.cursor()
crsr_select.execute("SELECT ...")
for row in crsr_select:
    crsr_insert.execute("INSERT ...")

相关问题 更多 >