这回依然是使用 insert批量插入这种方式

insert into emp(name,age,cdate)

values

('A' , 20, '2019-10-13 00:00:00'),

('B' , 21, '2019-10-13 01:00:00'),

('C' , 22, '2019-10-13 05:00:00')

只是执行SQL的方式由stmt.executeBatch换成了stmt.execute,结果发现速度上几乎一样。

代码如下:

package com.hy.action.jdbc;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

public class BatchJDBCStmtInsert2 {
    private static Logger logger = Logger.getLogger(BatchJDBCStmtInsert2.class);

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();

        //把beans.xml的类加载到容器
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jt=(JdbcTemplate)applicationContext.getBean("jdbcTemplate");

        // Initialize conn&stmt
        Connection conn=null;
        Statement stmt=null;

        try {
            conn =jt.getDataSource().getConnection();
            conn.setAutoCommit(false);
            stmt = conn.createStatement();

            String ctime="2017-11-01 00:00:01";
            int index=0;

            for(int i=0;i<10000;i++) {
                String insertSql="insert into emp(name,age,cdate) values ";
                List<String> list=new ArrayList<String>();

                for(int j=0;j<1000;j++) {
                    index++;

                    Object arr[]={"'E:"+index+"'",index % 100,"'"+ctime+"'"};
                    String valueSql=MessageFormat.format("({0},{1},{2})", arr);
                    list.add(valueSql);

                    ctime=timePastOneSecond(ctime);
                }

                String sql=insertSql+String.join(",", list);
                stmt.execute(sql);
                conn.commit();
                logger.info("#"+i+" 1000 records have been inserted to table:'emp'.");
            }
        } catch (SQLException e) {
            logger.error("Error happened:"+e);
            try {
                conn.rollback();
            } catch (SQLException e1) {
                logger.error("Can not rollback because of the error:'"+e+"'.");
            }
        }finally {
            try {
                stmt.close();
                conn.close();

                long endTime = System.currentTimeMillis();
                logger.info("Time elapsed:" + toDhmsStyle((endTime - startTime)/1000) + ".");
            } catch (SQLException e1) {
                logger.error("Can not close connection because of the error:'"+e1+"'.");
            }
        }
    }

    public static String timePastOneSecond(String otime) {
        try {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dt=sdf.parse(otime);

            Calendar newTime = Calendar.getInstance();
            newTime.setTime(dt);
            newTime.add(Calendar.SECOND,1);

            Date dt1=newTime.getTime();
            String retval = sdf.format(dt1);

            return retval;
        }
        catch(Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

     // format seconds to day hour minute seconds style
    // Example 5000s will be formatted to 1h23m20s
    public static String toDhmsStyle(long allSeconds) {
        String DateTimes = null;

        long days = allSeconds / (60 * 60 * 24);
        long hours = (allSeconds % (60 * 60 * 24)) / (60 * 60);
        long minutes = (allSeconds % (60 * 60)) / 60;
        long seconds = allSeconds % 60;

        if (days > 0) {
            DateTimes = days + "d" + hours + "h" + minutes + "m" + seconds + "s";
        } else if (hours > 0) {
            DateTimes = hours + "h" + minutes + "m" + seconds + "s";
        } else if (minutes > 0) {
            DateTimes = minutes + "m" + seconds + "s";
        } else {
            DateTimes = seconds + "s";
        }

        return DateTimes;
    }
}

控制台输出:

INFO [main] - #9990 1000 records have been inserted to table:'emp'.
 INFO [main] - #9991 1000 records have been inserted to table:'emp'.
 INFO [main] - #9992 1000 records have been inserted to table:'emp'.
 INFO [main] - #9993 1000 records have been inserted to table:'emp'.
 INFO [main] - #9994 1000 records have been inserted to table:'emp'.
 INFO [main] - #9995 1000 records have been inserted to table:'emp'.
 INFO [main] - #9996 1000 records have been inserted to table:'emp'.
 INFO [main] - #9997 1000 records have been inserted to table:'emp'.
 INFO [main] - #9998 1000 records have been inserted to table:'emp'.
 INFO [main] - #9999 1000 records have been inserted to table:'emp'.
 INFO [main] - Time elapsed:4m55s.

数据库的情况:

下面,就可以写总结了。

--END-- 2019年10月13日15:23:03

【JDBC】使用Spring提供的JDBCTemplate通过Statement向MySql数据库插入千万条数据,耗时4m55s,使用insert语句批量插入方式二的更多相关文章

  1. 【JDBC】使用Spring提供的JDBCTemplate通过PrepareStatement向MySql数据库插入千万条数据,耗时32m47s,速度提升有限

    数据库环境还和原来一样,只是从Statement换成了PrepareStatement,都说PrepareStatement因为预编译比Statement快,但是实际运行真快不了多少. 代码如下: p ...

  2. 使用JDBC向数据库中插入一条数据

    原谅我是初学者,这个方法写的很烂,以后不会改进,谢谢 /** * 通过JDBC向数据库中插入一条数据 1.Statement 用于执行SQL语句的对象 1.1 通过Connection 的 * cre ...

  3. Spring Boot入门(2)使用MySQL数据库

    介绍   本文将介绍如何在Spring项目中连接.处理MySQL数据库.   该项目使用Spring Data JPA和Hibernate来连接.处理MySQL数据库,当然,这仅仅是其中一种方式,你也 ...

  4. Java使用JDBC连接数据库逐条插入数据、批量插入数据、以及通过SQL语句批量导入数据的效率对比

    测试用的示例java代码: package com.zifeiy.test.normal; import java.io.File; import java.io.FileOutputStream; ...

  5. 使用JDBC(Dbutils工具包)来从数据库拿取map类型数据来动态生成insert语句

    前言: 大家在使用JDBC来连接数据库时,我们通过Dbutils工具来拿取数据库中的数据,可以使用new BeanListHandler<>(所映射的实体类.class),这样得到的数据, ...

  6. JDBC快速入门(附Java通过jar包连接MySQL数据库)

    •通过jar包连接mysql数据库 •下载jar包 Java 连接 MySQL 需要驱动包,官网下载地址为MySQL驱动包官网下载,选择适合的jar包版本进行安装 (记得安装的地址,下面导入包时会用到 ...

  7. spring mvc 插入一条数据 返回该数据的主键编号

    import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.suppo ...

  8. 使用JDBC向数据库中插入一条数据(第一次修改版)

    增加了一个Tools类,放了一些常用的工具 package com.JDBC.java; import java.io.IOException; import java.io.InputStream; ...

  9. spring boot使用log4j2将日志写入mysql数据库

    log4j2官方例子在spring boot中报错而且还是用的是org.apache.commons.dbcp包 我给改了一下使用org.apache.commons.dbcp2包 1.log4j2. ...

随机推荐

  1. 1 bootstrapValidator使用

    1 如何使用 引入 <link href="bootstrapValidator.min.css" rel="stylesheet"> css文件 ...

  2. kali linux 安装 qq (deepin-wine)

    添加deeepin-wine 依赖 /etc/apt/sources.list: # Generated by deepin-installer deb http://mirrors.aliyun.c ...

  3. List集合复制

    方法一: public static void main(String[] args) { // TODO Auto-generated method stub List<String> ...

  4. js实现复制 、剪切功能-clipboard.min.js 示例

    html: <div id="txt">我是要复制的内容</button> <button id="copyBtn">点击复 ...

  5. bitcoind搭建

    https://degreesofzero.com/article/installing-bitcoind-on-ubuntu.html1. sudo apt-get install python-s ...

  6. 接口自动化平台——httprunnermanager

    Windows 环境搭建 1. 下载安装pip install httprunner==1.4.2hrun -V #1.4.2har2case -V #0.1.8 2. httprunnermanag ...

  7. flyio 的请求封装

    1.安装flyio.js npm install flyio --save-dev 2.在util创建一个fly.js用于封装 import Vue from 'vue' var Fly=requir ...

  8. 1.安装Loucust

    python 3.x 通过pip安装: pip install locustio 如果是以分布式队列运行locust,需要装一种通信队列的库pyzmq  :pip install pyzmq 安装成功 ...

  9. 洛谷P2664 树上游戏——点分治

    原题链接 被点分治虐的心态爆炸了 题解 发现直接统计路径上的颜色数量很难,考虑转化一下统计方式.对于某一种颜色\(c\),它对一个点的贡献为从这个点出发且包含这种颜色的路径条数. 于是我们先点分一下, ...

  10. MFC 模态对话框、非模态对话框

    modal dialogs与modeless dialogs,modal dialogs会让原窗体不被选中,modeless dialogs原窗体依然可以选中. 1.模态对话框的显示 DlgModal ...