python update mysql
3548 ワード
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
def selectfunc():
sql1 = "SELECT * FROM lancome15_order_online WHERE ogn<0 and statstatus=11" #oid,otime,uid,gid,ogn,amount
cursor.execute(sql1)
numrows = int(cursor.rowcount)
print numrows
d = {}
for i in range(numrows):
L = cursor.fetchone()
d[i] = L
return d
def find_and_update():
d = selectfunc()
num = 0
for k in d.keys():
fotime = d[k][1]
fuid = d[k][2]
fgid = d[k][3]
fogn = -d[k][8]
famount = -d[k][10]
#print fotime,fuid,fgid,fogn,famount
sql2 = " select * from lancome15_order_online where otime <='%s' and uid = '%s' and gid = '%s' and ogn >= %d and amount >= \
%d order by otime desc limit 1" % (fotime, fuid, fgid, fogn, famount)
cursor.execute(sql2)
g = cursor.fetchone()
if g is None:
continue
else:
goid = g[0]
guid = g[2]
ggid = g[3]
gogn = g[8]
sql3 = "update lancome15_order_online set statstatus=11 where oid = '%s' and uid = '%s' and gid = '%s' and ogn = %d " % ( goid, guid, ggid, gogn)
cursor.execute(sql3)
results2 = cursor.fetchone()
db.commit()
num += 1
#print num
#print "Over",'
'
print "All over"
if __name__=="__main__":
db = MySQLdb.connect("localhost","root","111111","work")
cursor = db.cursor()
find_and_update()
db.close()
今日データ分析をするときは、1枚の表に返品記録(ラベルは11)を見つけ、返品記録に基づいて対応する購入記録を見つけ、購入記録のラベルを1から11に変更する必要があります.最初の考え方は、表の返品記録をループして検索し、1つ見つけるたびに対応する購入記録を検索して更新しますが、プログラムが更新記録を実行すると次の返品記録を検索できません(原因は分かりません).その後、ポリシーを変更し、すべての返品記録を辞書に見つけて保存し、その後のプロセスは正常に実行されます.