我正在尝试在表中保存一些数据,如果更改,则更新该值。
def saveobject(obj):
save=(obj.field1, obj.field2, obj.field3)
con = sqlite3.connect('test.db')
with con:
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS Users(field1 TEXT, field2 INT, field3 INT)")
allrows = cur.fetchall()
print allrows
if(len(allrows)==0):
cur.execute("INSERT INTO Users VALUES(?,?,?)", save)
else:
for row in allrows:
if(obj.field1==row[0]):
if(obj.field2==row[1]):
print 'Object already Present'
break
else:
print 'Object field2 updated'
cur.execute("UPDATE Users set field2=(?) where field1=(?)", (obj.field2, obj.field1))
break
else:
cur.execute("INSERT INTO Users VALUES(?,?,?)", save)
print 'User added'
print 'after ', cur.fetchall()
运行程序,验证方法是否正确接收了对象(我验证了打印"保存"一切正常),我有以下输出:
[]
after []
我做错了什么?
答案 0 :(得分:1)
cur.execute("CREATE TABLE IF NOT EXISTS Users(field1 TEXT, field2 INT, field3 INT)")
allrows = cur.fetchall()
for row in allrows:
allrows
的长度始终为零,因为“create table”不会返回一行。