python

python 操作mysql数据库

2019-06-25  本文已影响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()
上一篇 下一篇

猜你喜欢

热点阅读