Java使用JDBC连接数据库逐条插入数据、批量插入数据、以及通过SQL语句批量导入数据的效率对比
测试用的示例java代码:
package com.zifeiy.test.normal;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.exec.ExecuteException;
public class Test20181120 {
public static void main(String[] args) throws ExecuteException, IOException, ClassNotFoundException, SQLException {
// 生成1万条测试数据
List<TestObject> testObjectList = new ArrayList<TestObject>();
for (int i = 0; i < 10000; i ++) {
testObjectList.add(new TestObject());
}
// 生成CSV文件
File csvFile = new File("D:\\test.csv");
FileOutputStream fos = new FileOutputStream(csvFile);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
String content = "";
for (TestObject e : testObjectList) {
content += e.toCsvLine();
}
osw.write(content);
osw.flush();
// MySQL依次执行1万条Insert的SQL
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=UTF8&rewriteBatchedStatements=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&useSSL=false", "root", "password");
Statement statement = connection.createStatement();
// drop table的SQL
String dropTableSQL = "drop table if exists test_table";
// create table的SQL
String createTableSQL = "create table test_table ( id integer, name varchar(20), age integer, brief varchar(100) )";
long beginTime, endTime;
// 使用JDBC一次插入
statement.execute(dropTableSQL);
statement.execute(createTableSQL);
beginTime = System.currentTimeMillis();
for (TestObject e : testObjectList) {
statement.execute(e.toInsertSQL());
}
endTime = System.currentTimeMillis();
System.out.println("timer 1 : " + (endTime - beginTime) + " ms");
// 使用JDBC批量插入
statement.execute(dropTableSQL);
statement.execute(createTableSQL);
beginTime = System.currentTimeMillis();
for (TestObject e : testObjectList) {
statement.addBatch(e.toInsertSQL());
}
statement.executeBatch();
endTime = System.currentTimeMillis();
System.out.println("timer 2 : " + (endTime - beginTime) + " ms");
// 使用SQL批量导入CSV文件内容
statement.execute(dropTableSQL);
statement.execute(createTableSQL);
beginTime = System.currentTimeMillis();
statement.execute(
"load data local infile 'd:\\\\test.csv' \r\n" +
"into table testdb.test_table character set utf8\r\n" +
"fields terminated by ',' optionally enclosed by '\"' escaped by '\"' \r\n" +
"lines terminated by '\\r\\n'"
);
statement.executeBatch();
endTime = System.currentTimeMillis();
System.out.println("timer 3 : " + (endTime - beginTime) + " ms");
}
static class TestObject {
private Integer id;
private String name;
private Integer age;
private String brief;
public TestObject() {
this.id = (int) ( Math.random() * 1e9);
this.name = (id % 4 == 0) ? "刘德华" : ( (id % 4 == 1) ? "周杰伦" : ( (id % 4 == 2) ? "麦哲伦" : "范晓萱" ) );
this.age = (int) (Math.random() * 100 );
this.brief = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
}
public String toInsertSQL() {
return String.format("insert into test_table (id, name, age, brief) values (%d, '%s', %d, '%s')", id, name, age, brief);
}
public String toCsvLine() {
return String.format("%d,\"%s\",%d,\"%s\"\r\n", id, name, age, brief);
}
}
}
其中,我们首先创造了1万条随机数据,然后生成这1万条数据对应的CSV文件,
然后我们通过以下三种方式进行对这1万条数据:
- 使用JDBC逐条插入;
- 使用JDBC批量插入;
- 使用
load dataSQL语句导入CSV文件。
执行的结果如下:
结果1
timer 1 : 31417 ms
timer 2 : 27559 ms
timer 3 : 239 ms
结果2
timer 1 : 31428 ms
timer 2 : 28009 ms
timer 3 : 223 ms
结果3
timer 1 : 30779 ms
timer 2 : 30969 ms
timer 3 : 441 ms
可以发现,使用SQL批量导入文本文件的方法明显比JDBC插入快不止一个数量级。
Java使用JDBC连接数据库逐条插入数据、批量插入数据、以及通过SQL语句批量导入数据的效率对比的更多相关文章
- 如何用SQL语句查询Excel数据?
如何用SQL语句查询Excel数据?Q:如何用SQL语句查询Excel数据? A:下列语句可在SQL SERVER中查询Excel工作表中的数据. 2007和2010版本: SELECT*FROMOp ...
- java通过jdbc连接数据库并更新数据(包括java.util.Date类型数据的更新)
一.步骤 1.获取Date实例,并通过getTime()方法获得毫秒数: 2.将获取的毫秒数存储到数据库中,注意存储类型为nvarchar(20): 3.读取数据库的毫秒数,作为Date构造方法的参数 ...
- Java开发JDBC连接数据库
Java开发JDBC连接数据库 创建一个以JDBC连接数据库的程序,包含6个步骤: JDBC五部曲1.加载驱动2.获得链接3.获取statement对象 4.执行SQL语句5.产生resultset对 ...
- 关于Java(JDBC连接数据库)
Processing SQL Statements with JDBC 处理JDBC中的SQL语句 这节主要是 JDBC 与数据库交互的基本步骤 JDBC的基石是DriverManager,通过它,J ...
- log4j向oracle中插入一条系统当前时间的sql语句
配置log4j,要向oracle插入一条系统当前时间的sql语句,按网上查找的总是出现各种各样的报错,最后总结出的写法是: ### shezhi### log4j.rootLogger = debug ...
- SQL反模式学习笔记18 减少SQL查询数据,避免使用一条SQL语句解决复杂问题
目标:减少SQL查询数据,避免使用一条SQL语句解决复杂问题 反模式:视图使用一步操作,单个SQL语句解决复杂问题 使用一个查询来获得所有结果的最常见后果就是产生了一个笛卡尔积.导致查询性能降低. 如 ...
- 数据库函数:sqlite3_exec() SQL语句
函数:sqlite3_exec(),称为便捷函数,封装了好多任务. 函数声明: int sqlite3_exec( sqlite * , const char * sql , sqlite_c ...
- SQL Server高速导入数据分享
SQL Server高速导入数据,能够尝试的方法例如以下:CTE.OpenRowSet/OpenDataSource.BULK INSERT.bcp.Shell. 以下依次介绍这几种办法. 1.CTE ...
- 使用Sql语句快速将数据表转换成实体类
开发过程中经常需要根据数据表编写对应的实体类,下面是使用sql语句快速将数据表转换成对应实体类的代码,使用时只需要将第一行'TableName'引号里面的字母换成具体的表名称就行了: declare ...
随机推荐
- Jenkins 参数化构建(Extended Choice Parameter)
1.下载安装 Extended Choice Parameter 插件 2.打开job--->General--->参数化构建过程--->Extended Choice Parame ...
- [51Nod 1238] 最小公倍数之和 (恶心杜教筛)
题目描述 求∑i=1N∑j=1Nlcm(i,j)\sum_{i=1}^N\sum_{j=1}^Nlcm(i,j)i=1∑Nj=1∑Nlcm(i,j) 2<=N<=10102<=N ...
- [CSS] Conditionally Assign Style to a Parent Element with Focus-Within Pseudo-class
Use the focus-within pseudo-class to conditionally assign styling to a parent element when its child ...
- 009——C#全局变量定义
(一)窗体二定义,static静态 public static byte[] waveform_data = { }; // 数据,在串口接收中变化 public static bool wavefo ...
- mongodb 开发规范
一.命名规则 1.数据库命名规则 数据库名可以是满足以下条件的任意UTF-8字符串: (1)不能是空字符串(”") : (2)不能含有”(空格)...$./..和(空字符): (3)应全部小 ...
- HashMap的底层结构和原理
http://youzhixueyuan.com/the-underlying-structure-and-principle-of-hashmap.html HashMap是Java程序员使用频率最 ...
- 小象和老鼠 DP
小象和老鼠 DP \(N*M\)的网格图,格子\((i,j)\)有\(A_{i,j}\)个老鼠,问小象从左上角\((1,1)\)走到右下角\((N,M)\)看到的最少老鼠.小象可以看见老鼠,当且仅当老 ...
- P2679 子串 DP
P2679 子串 DP 从字符串A中取出\(k\)段子串,按原顺序拼接,问存在多少个方案使拼接的字符串与字符串B相同 淦,又是这种字符串dp 设状态\(ans[i][j][k]\)表示A串位置\(i\ ...
- PHP全栈学习笔记27
数组概述,类型,声明,遍历,输出,获取数组中最后一个元素,删除重复数组,获取数组中指定元素的键值,排序,将数组中的元素合成字符串. 数组概述,数组是存储,管理和操作一组变量. 数组类型为一维数组,二维 ...
- VMware安装Centos7超详细教程
本篇文章主要介绍了VMware安装Centos7超详细过程(图文),具有一定安装参考价值 在没有运维的情况下,很多时候测试需要自己搭建测试环境,而测试环境又分为QA环境,自动化测试环境,uat环境,以 ...