python update mysql

#!/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。一开始的思路是:循环查找表格里的退货记录,每找到一条就搜索对应的购买记录,然后更新,但是程序执行更新一条记录后就不能搜索下一条退货记录了(原因不知)。然后改变了策略,将所有退货记录找出并存入字典,之后的过程就可以正常运行了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值