【问题标题】:Why does "c.execute(...)" break the loop?为什么“c.execute(...)”会打破循环?
【发布时间】:2010-12-17 10:46:34
【问题描述】:

我正在尝试更改 sqlite3 文件中的一些数据,而我在 python 和 google-fu 中不存在的知识使我最终得到了以下代码:

#!/usr/bin/python
# Filename : hello.py

from sqlite3 import *

conn = connect('database')

c = conn.cursor()

c.execute('select * from table limit 2')

for row in c:
    newname = row[1]
    newname = newname[:-3]+"hello"
    newdata = "UPDATE table SET name = '" + newname + "', originalPath = '' WHERE id = '" + str(row[0]) + "'"
    print row
    c.execute(newdata)
    conn.commit()
c.close()

它在第一行就像一个魅力,但由于某种原因,它只运行一次循环(只有表中的第一行被修改)。当我删除“c.execute(newdata)”时,它应该循环遍历表中的前两行。如何让它发挥作用?

【问题讨论】:

    标签: python sqlite


    【解决方案1】:

    这样做是因为一旦您执行c.execute(newdata),光标就不再指向原始结果集。我会这样做:

    #!/usr/bin/python
    # Filename : hello.py
    
    from sqlite3 import *
    
    conn = connect('database')
    
    c = conn.cursor()
    
    c.execute('select * from table limit 2')
    result = c.fetchall()
    
    for row in result:
        newname = row[1]
        newname = newname[:-3]+"hello"
        newdata = "UPDATE table SET name = '" + newname + "', originalPath = '' WHERE id = '" + str(row[0]) + "'"
        print row
        c.execute(newdata)
    conn.commit()    
    c.close()
    conn.close()
    

    【讨论】:

      【解决方案2】:

      当您调用c.execute(newdata) 时,它会更改光标c 以便for row in c: 立即退出。

      试试:

      c = conn.cursor()
      c2 = conn.cursor()
      
      c.execute('select * from table limit 2')
      
      for row in c:
          newname = row[1]
          newname = newname[:-3]+"hello"
          newdata = "UPDATE table SET name = '" + newname + "', originalPath = '' WHERE id = '" + str(row[0]) + "'"
          print row
          c2.execute(newdata)
          conn.commit()
      c2.close()
      c.close()
      

      【讨论】:

      • 你真的不需要 2 个游标吧?只需保存第一次执行调用的结果并对其进行迭代。
      【解决方案3】:

      因为在循环内重复使用“c”会使您用作循环迭代器的“c”无效。为循环中的查询创建一个单独的光标。

      【讨论】:

        【解决方案4】:

        您正在使用相同的游标进行更新,更新不返回任何行,因此 c 中的行计算为 false。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-02-05
          • 1970-01-01
          • 2020-10-04
          • 1970-01-01
          • 2021-12-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多