利用python3插入多条MySQL语句(python脚本)

下载模块

pip3 install pymysql

python脚本

#!/usr/bin/python3
#插入多数据
#导入模块
import pymysql
li = []
#创建连接
conn = pymysql.connect(
    host='127.0.0.1',
    port=3306,
    user='root',
    passwd='123456',
    db='host_info',
    charset='utf8mb4'
)
# 获取游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 定义想要插入的数据数据
base_info = [{
    "manufacturer": "VMware, Inc.",
    "pod_name": "VMware7,1",
    "sn": "VMware-56 4d 2d 4c 91 1e 48 15-5b d2 73 9c ec 98 da 22",
    "host_name": "sharkyum.com",
    "kernel": "3.10.0-957.el7.x86_64",
    "os": "CentOS Linux release 7.6.1810 (Core)",
    "cpu_name": "Intel(R) Core(TM) i5-5350U CPU @ 1.80GHz"},
    {
    "manufacturer": "VMware, Inc.",
    "pod_name": "VMware7,1",
    "sn": "VMware-56 4d 2d 4c 91 1e 48 15-5b d2 73 9c ec 98 da 22",
    "host_name": "sharkyum.com",
    "kernel": "3.10.0-957.el7.x86_64",
    "os": "CentOS Linux ",
    "cpu_name": "Intel(R) Core(TM) i5-5350U CPU @ 1.80GHz"}]
#定义sql语句
sql = '''
    insert into base_info(
    manufacturer, pod_name,
    sn, host_name,
    kernel, os, cpu_name)
    values(%s, %s, %s, %s, %s, %s, %s);'''
def foo():
    #把数据放到列表中
    for i in base_info:
        infos = tuple(i.values())
        li.append(infos)
# 执行 sql 语句
    cursor.executemany(sql, li)
    # 提交更改
    conn.commit()
    # 关闭游标对象
    cursor.close()
    # 关闭连接对象
    conn.close()
foo()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值