python3 读取excel表中的数据并插入到数据库中

#!/usr/bin/python
# -*- coding: utf-8 -*-
import pymysql
import pandas as pd
import sys

def get_assets():
    assets = pd.read_excel(sys.argv[1])
    ip = assets ['IP'].astype('str')
    price = assets ['金额'].astype('str')
    ip_price_dict  = dict(zip(ip,price))
    return ip_price_dict



def update_data():
    # 打开数据库连接
    db = pymysql.connect("localhost","root","123456","cmdb" )
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()
     
     
    for key,value in ip_price_dict.items():
        print(value)
        sql1 = "SELECT * from assets_asset where manage_ip = '%s'" % (key)
        cursor.execute(sql1)
        result = cursor.fetchone()
     
        if result!=None:
            sql2 = "UPDATE assets_asset SET price = '%s' WHERE manage_ip = '%s'" % (value,key)
            try:
               # 执行sql语句
               cursor.execute(sql2)
               # 执行sql语句
               db.commit()
               print("update ok")
            except:
               # 发生错误时回滚
               db.rollback()
    # 关闭数据库连接
    db.close()


if __name__ == '__main__':
    # 读取excel数据
    ip_price_dict  = get_assets()

    # 插入数据
    update_data()

 

你可能感兴趣的:(python)