Use UPDATE in a loop

百般思念 提交于 2019-12-24 16:24:36

问题


When I execute the following code:

for acc_row in cursor.execute("select * from tabela1"):
    cursor.execute("UPDATE table_name SET column_name=? where column_name=?", ('some_value','some_value'))

I receive the following error referencing the line containing the for loop:

ProgrammingError: No results. Previous SQL was not a query

The for loop works fine without the update statement, and vice versa

Software:

Python 2.7
Windows
pyodbc 3.0.7
AccessDatabaseEngine for MS Access 2010


回答1:


You are relying on the state of the cursor. object to control the for loop, but then you are modifying that object (by executing the UPDATE statement) inside the loop. You'll need to maintain two cursor objects, one to control the loop and another one to perform the UPDATEs.




回答2:


If your result set isn't large this should work:

rows = cursor.execute('select * from tabela1').fetchall()
for acc_row in rows:
    cursor.execute('UPDATE table_name SET column_name=? where column_name=?', (acc_row.column1, acc_row.column2))

If the result set is too large to load into memory, maintain two cursors as mentioned in Gord Thompson's answer.



来源:https://stackoverflow.com/questions/18131329/use-update-in-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!