0
点赞
收藏
分享

微信扫一扫

Python dict 插入mysql

import pymysql
vm_info = [{'name': '192.168.1.2-network-devops', 'owner': 'wangxin.jeffry', 'IP': '10.0.17.2', 'region': None,
             'os_platform': None,'desc': '1、zabbix agent使用6.2版本,主动模式监控 2、更新系统yum update -y'}, 
           {'name': '192.168.1.3-network-devops', 'owner': 'wangxin.jeffry', 'IP': '10.0.17.3', 'region': None, 
             'os_platform': None, 'desc': '1、zabbix agent使用6.2版本,主动模式监控 2、更新系统yum update -y'}]

#普通插入方式

def insert_data(db):
    # 创建游标对象
    cursor = db.cursor()
    # 向vm_info中插入数据
    for i in vm_info:
    	vm_name = i["name"]
        owner = i["owner"]
        IP = i["IP"]
        region = i["region"]
        os_platform = i["os_platform"]
        desc = i["desc"]
        insert_sql = """
        INSERT INTO vm_info(vm_name,owner,IP,region,os_platform,vm_desc)
        VALUES (%s,%s,%s,%s,%s,%s)"""
        # 执行添加数据的SQL语句
        cursor.execute(insert_sql,(vm_name,owner,IP,region,os_platform,desc))
    # 提交事务
    db.commit()
    # 关闭Cursor
    cursor.close()

#高级插入方式

def insert_data(db):
    # 创建游标对象
    cursor = db.cursor()
    # 向vm_info中插入数据
    cursor.executemany("""
             INSERT INTO vm_info(vm_name,owner,IP,region,os_platform,vm_desc)
             VALUES (%(name)s,%(owner)s,%(IP)s,%(region)s,%(os_platform)s,%(desc)s)""", vm_info)
    # 提交事务
    db.commit()
    # 关闭Cursor
    cursor.close()

举报

相关推荐

0 条评论