美文网首页python
python 操作mysql数据库

python 操作mysql数据库

作者: 迷糊银儿 | 来源:发表于2019-06-25 17:02 被阅读0次

    下载并安装# MySQLdb的安装与使用

    yum install MySQL-python
    
    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    import MySQLdb,json
    
    # 打开数据库连接
    conn = MySQLdb.connect(host="123.342.172.59",user = "user",passwd = "passwd" ,db="ddd",port= 8500,charset="utf8")
    # 使用cursor()方法获取操作游标
    cursor = conn.cursor() #获取游标
    
    sql = "select * from product_meta"
    
    try:
        cursor.execute(sql)    #执行sql
        data=cursor.fetchall()   #获取查询结果
        #data=cursor.fetchone()   #获取查询结果
        for item  in data:
            pid = item[2]
            print("pid",type(pid),pid)
            ext_info=item[7]
            s=json.loads(ext_info)
            cash = s["cash"]
            print("cash",type(cash))
            sql1="insert into rule (productid,bussid,type,flag,fir_reward) values(%(pid)s,1,1,1,%(cash)s)"
            value={"pid":pid,"cash":cash}
            cursor.execute(sql1,value)
            print(cash)
            conn.commit()
    except:
       # Rollback in case there is any error
       conn.rollback()
    
    
    cursor.close() #关闭游标
    # 关闭数据库连接
    conn.close()
    

    相关文章

      网友评论

        本文标题:python 操作mysql数据库

        本文链接:https://www.haomeiwen.com/subject/ewatcctx.html