#!/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",'\n'
print "All over"
if __name__=="__main__":
db = MySQLdb.connect("localhost","root","111111","work")
cursor = db.cursor()
find_and_update()
db.close()
今天做数据分析的时候,需要在一张表里找到退货记录(标签为11),然后根据退货记录找到其对应的购买记录,将购买记录的标签由1改为11。一开始的思路是:循环查找表格里的退货记录,每找到一条就搜索对应的购买记录,然后更新,但是程序执行更新一条记录后就不能搜索下一条退货记录了(原因不知)。然后改变了策略,将所有退货记录找出并存入字典,之后的过程就可以正常运行了。