Python “为什么?”;c、 执行(…)”;打破循环?
我试图更改sqlite3文件中的一些数据,但我对python和google fu的不了解使我最终得到以下代码:Python “为什么?”;c、 执行(…)”;打破循环?,python,sqlite,Python,Sqlite,我试图更改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] ne
#!/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)”时,它会像应该的那样循环表中的前两行。如何使其工作?当您调用
c.execute(newdata)
时,它会更改光标c
,使c:中的行的立即退出
尝试:
因为在循环中重用“c”会使用作循环迭代器的“c”无效。为循环中的查询创建一个单独的游标。您使用相同的游标进行更新,更新不会返回任何行,因此对于c中的行,计算为false。这样做是因为一旦执行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()
不过你并不需要两个光标,是吗?只需保存第一次执行调用的结果并迭代即可。
#!/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()