List数据分批插入

public void batchInsertTable(List<InsertObjClass> list, int startIndex, int maxSize){
    if (startIndex + maxSize >= list.size()){
        dao.insertList(list.subList(startIndex, list.size()));
    }else{
        dao.insertList(list.subList(startIndex, startIndex + maxSize));
        this.batchInsertTable(list, startIndex + maxSize, maxSize);
    }
}

其中,InsertObjClass为对象类,insertList为批量插入的方法。

下面为Mysql中在mybatis中批量插入数据的方法:

1.首先定义接口:

public int insertList(List<insertList> list);

2.在对应的xml文件中实现上面的方法:

    <insert id="insertList" parameterType="java.util.ArrayList">
        insert into table
        (id,name,age)
        values
        <foreach collection="list" item="item" index="index" separator=",">
            (
                #{item.id},
                #{item.name},
                #{item.age}
            )
        </foreach>
    </insert>

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用SQL的INSERT语句来将一批数据分批插入数据库。具体的实现方式取决于你所使用的数据库管理系统。以下是一个简单的示例,假设你使用的是MySQL数据库: ```python import pymysql # 假设你的数据已经按照需要的批次划分为多个列表,每个列表包含多个元组,每个元组表示一条数据 data_batches = [ [('John', 25), ('Jane', 30), ('David', 28)], [('Michael', 32), ('Emily', 27), ('Daniel', 29)], [('Olivia', 31), ('Jacob', 26), ('Sophia', 33)] ] # 连接到数据库 connection = pymysql.connect(host='localhost', user='your_username', password='your_password', db='your_database') try: # 创建游标对象 cursor = connection.cursor() # 遍历每个数据批次 for data_batch in data_batches: # 使用 executemany() 方法批量插入数据 cursor.executemany('INSERT INTO your_table (name, age) VALUES (%s, %s)', data_batch) # 提交事务 connection.commit() finally: # 关闭游标和连接 cursor.close() connection.close() ``` 在上述示例中,我们通过`executemany()`方法一次性插入了多个数据批次,每个数据批次都是一个包含多个元组的列表。通过在SQL语句中使用占位符 `%s`,我们指定了要插入数据的位置。你需要根据实际情况修改示例中的数据库连接参数、表名和字段名。 请注意,这只是一个简单的示例,实际情况可能会有所不同。具体的实现方式可能因使用的数据库管理系统、编程语言和数据库驱动程序而有所差异。因此,你可能需要根据自己的情况进行适当的调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值