Python dict 插入mysql
  Dzhz6XExdadR 2023年11月02日 20 0
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()
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  9JCEeX0Eg8g4   2023年11月25日   41   0   0 ednpython
  eHipUjOuzYYH   2023年12月10日   30   0   0 mysqlsqlUser
  hHWnOnebRjW2   2023年11月27日   25   0   0 PostgreSQLsqlbash