这回依然是使用 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. 关于google开源的Material Design说明

    原文地址:https://github.com/MaterialDesignInXAML/MaterialDesignInXamlToolkit/wiki/Getting-Started 源码地址:h ...

  2. 如何使用cgdb(一)——窗口切换

    cgdb是一个轻量级的基于控制台的多窗口gdb调试界面.除了标准的gdb控制台之外,cgdb还提供了一个分屏视图,可以在执行的时候显示具备语法高亮的源代码.键盘控制是仿照vim设计的,所以vim用户使 ...

  3. 本地套接字-本地socket

    本地套接字简单应用场景 一 #服务端--简单 import socket import os a='sock_file' if os.path.exists(a): os.remove(a) s=so ...

  4. JEESZ-SSO解决方案

    提醒:文档只是作为一个基础的参考,愿意了解的朋友可以随时咨询. 第一节:单点登录简介 第一步:了解单点登录 SSO主要特点是: SSO应用之间使用Web协议(如HTTPS),并且只有一个登录入口. S ...

  5. Java多线程(一)——线程基础和锁锁锁

    目录 Java多线程(一) 一.线程的定义 二.Synchronize线程同步 三.偏向锁.自旋锁.重量级锁 四.volatile关键字 五.Compare And Swap无锁自旋优化技术和ABA版 ...

  6. PAT Basic 1064 朋友数 (20 分)

    如果两个整数各位数字的和是一样的,则被称为是“朋友数”,而那个公共的和就是它们的“朋友证号”.例如 123 和 51 就是朋友数,因为 1+2+3 = 5+1 = 6,而 6 就是它们的朋友证号.给定 ...

  7. 手摸手教你让Laravel开发Api更得心应手

    https://www.guaosi.com/2019/02/26/laravel-api-initialization-preparation/ 1. 起因 随着前后端完全分离,PHP也基本告别了v ...

  8. MNPR--造福人类的人值得被感激

    https://artineering.io/research/MNPR/ https://mnpr.artineering.io https://pdfs.semanticscholar.org/0 ...

  9. formData+ajax文件上传

    html代码: <form class="form-horizontal" enctype="multipart/form-data" method=&q ...

  10. c++ 用eclipse建立一个类,并实例化并运行

    新建项目 file->new->c/c++ project 项目结构 cpc.cpp //================================================= ...