python – 为什么“c.execute(…)”打破循环?
发布时间:2020-12-20 11:16:18 所属栏目:Python 来源:网络整理
导读:我正在尝试更改sqlite3文件中的一些数据,而我在 python和google-fu中不存在的知识让我最终得到了这段代码: #!/usr/bin/python# Filename : hello.pyfrom sqlite3 import *conn = connect('database')c = conn.cursor()c.execute('select * from table limit
我正在尝试更改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)”时,它会循环遍历表中的前两行,就像它应该的那样.我如何使其工作? 解决方法
这样做是因为只要你执行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() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |