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

代码如下:

package com.hy.action.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

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

public class BatchJDBCPstmtInsert {
    private static Logger logger = Logger.getLogger(BatchJDBCPstmtInsert.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&pstmt
        Connection conn=null;
        PreparedStatement pstmt = null; 

        try {
            conn =jt.getDataSource().getConnection();
            conn.setAutoCommit(false);
            pstmt = conn.prepareStatement("insert into emp(name,age,cdate) values (?,?,?)");

            String ctime="2017-11-01 00:00:01";
            long clong=getVlaueFrom(ctime);

            int index=0;

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

                    pstmt.setString(1,"'E:"+index+"'");
                    pstmt.setInt(2, index % 100);
                    pstmt.setTimestamp(3, new Timestamp(clong));
                    pstmt.addBatch();

                    clong+=1000;
                }

                pstmt.executeBatch();
                pstmt.clearBatch();
                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 {
                pstmt.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+"'.");
            }
        }
    }

    private static long getVlaueFrom(String timeStr) {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dt;
            try {
                dt = sdf.parse(timeStr);
                return dt.getTime();
            } catch (ParseException e) {
                logger.error("Can not parse '"+timeStr+"' to format'yyyy-MM-dd HH:mm:ss'.");

                return -1;
            }
    }

     // format seconds to day hour minute seconds style
    // Example 5000s will be formatted to 1h23m20s
    private 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:32m47s.

数据库的情况:

--END-- 2019年10月13日14:35:50

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

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

    这回依然是使用 insert批量插入这种方式 insert into emp(name,age,cdate) values ('A' , 20, '2019-10-13 00:00:00'), ('B ...

  2. mysql数据库插入数据获取自增主键的三种方式(jdbc PreparedStatement方式、mybatis useGeneratedKeys方式、mybatis selectKey方式)

    通常来说对于mysql数据库插入数据获取主键的方法是采用selectKey的方式,特别是当你持久层使用mybatis框架的时候. 本文除此之外介绍其它两种获取主键的方式. 为了方便描述我们先建一张my ...

  3. 【JDBC】Mysql海量数据插入——PreparedStatement加快数据插入

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/5861959.html 使用JDBC连接数据库时,如果插入的数据量大,一条一条地插入数据会变得非常缓慢.此时,我 ...

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

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

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

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

  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. spring boot使用log4j2将日志写入mysql数据库

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

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

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

随机推荐

  1. RabbitMQ的持久化(六)

    RabbitMQ的持久化主要体现在三个方面,即交换机持久化,队列持久化及消息持久化 注意,因公司使用php-amqplib来实现RabbitMQ,故之后举例说明的代码均使用的php-amqplib,而 ...

  2. RabbitMQ的特点与应用场景(二)

      1.RabbitMQ的主要特点 (1)可靠性:RabbitMQ可通过队列持久化,交换机持久化,消息持久化及ACK回应等机制保证可靠性 (2)支持多种语言与协议:RabbitMQ几乎支持所有的编程语 ...

  3. php-amqplib库操作RabbitMQ

    RabbitMQ基本原理 首先,建议去大概了解下RabbitMQ(以下简称mq)的基本工作原理,可以参考这篇文章最主要的几个对象如下 对象名称   borker 相当于mq server channe ...

  4. MySQL的sql_mode参数之NO_AUTO_VALUE_ON_ZERO对主键ID为0的记录影响

    最近遇到一个不合理使用数据库进行项目开发最终导致项目进度受阻的一个问题,某天几位开发人员找到我并告知数据库中某张表数据无法写入,又告知某行记录被删除了,因为被删除的记录对开发框架影响很大,他们已尝试重 ...

  5. tempfile:临时文件系统对象

    介绍 想要安全的创建名字唯一的临时文件,以防止被试图破坏应用或窃取数据的人猜出,这很有难度.tempfile模块提供了多个函数来安全创建临时文件系统资源.TemporaryFile函数打开并返回一个未 ...

  6. PXC节点启动与关闭

    PXC节点启动与关闭 最后关闭的PXC节点是安全退出时. cat /var/lib/mysql/grastate.dat,其中safe_to_bootstrap: 1,再次启动集群是则先启动该节点 s ...

  7. [Abp vNext微服务实践] - 前后端分类

    一.前景 abp vNext是ABP 开源 Web应用程序框架,是abp的新一代开源web框架.框架完美的集成.net core.identity server4等开源框架,适用于构建web应用程序和 ...

  8. P5074 Eat the Trees

    思路 同样是插头DP,但是这题因为可以形成多个回路,所以左右括号是没有区别的,只需要01就可以表示了 注意if的嵌套关系 注意全零矩阵也要输出1 代码 #include <cstdio> ...

  9. Rasterize order group

    增加shade 这里的并行 可以让更多 ...并行只在write那里wait 语法 struct I {float a [[raster_order_group(0)]];};

  10. 1.打开windows中功能的快捷方式

    1.打开组策略 命令:gpedit.msc 2.打开注册表 命令:regedit 3.快速打开本地安全组策略 命令:secpol.msc 4.打开服务 命令:services.msc 5.系统退域的时 ...