【发布时间】:2013-11-23 19:53:26
【问题描述】:
在下面的代码中,实际显示在数据库中的唯一提交是找到的最后一个“idn”。 idn 只是一个标识号,用于计算每个客户有多少个机顶盒。因此,如果 idn 1,2 和 3 都存在,它只会在应该正确 1,2 和 3 时将 3 写入 DB。如果 idn 1 是唯一存在的,那么它会被写入。谢谢你的帮助!
if "STBSINFO||" in line:
head, sep, tail = line.partition('STBSINFO||')
idn = idn + 1
if "|" in tail:
head, sep, tail = tail.partition('|')
#Creates the mac address variable from the partition
mac = head
if "|" in tail:
head, sep, tail = tail.partition('|')
#Gathers the IP of the given set top box
stbip = head
if idn == 1:
cursor.execute("INSERT OR REPLACE INTO packages (cid, mstb1) VALUES (?,?)", (cid, stbip))
conn.commit()
elif idn == 2:
cursor.execute("INSERT OR REPLACE INTO packages (cid, mstb2) VALUES (?,?)", (cid, stbip))
conn.commit()
elif idn == 3:
cursor.execute("INSERT OR REPLACE INTO packages (cid, mstb3) VALUES (?,?)", (cid, stbip))
conn.commit()
elif idn == 4:
cursor.execute("INSERT OR REPLACE INTO packages (cid, mstb4) VALUES (?,?)", (cid, stbip))
conn.commit()
【问题讨论】:
-
你确定不是插入或替换
1,然后插入或替换2(替换1),然后插入或替换-3(替换2)?如果您不知道……首先,如果您不想替换值,为什么要使用INSERT OR REPLACE;其次,请发布packages表的架构,以便其他人可以为您解决。 -
我正在使用 INSERT OR REPLACE 因为信息可能会因月而异。我从旧系统中获得了一个输出文件,然后使用这个 python 程序来理解它。如果有更好的方法,我愿意接受。为什么 2 上的 INSERT OR REPLACE 会替换 1?它们是表中的不同列。这是我用来创建表的: cursor.execute("""CREATE TABLE packages(cid TEXT, mstb1 TEXT, mstb2 TEXT, mstb3 TEXT, mstb4 TEXT, PRIMARY KEY (cid))
-
我认为你不明白
INSERT OR REPLACE做了什么。它插入一个全新的行,用您的新行完全替换任何冲突的行。它不会更改现有行中的值。看我的回答。