测试用的示例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语句批量导入数据的效率对比的更多相关文章

  1. 如何用SQL语句查询Excel数据?

    如何用SQL语句查询Excel数据?Q:如何用SQL语句查询Excel数据? A:下列语句可在SQL SERVER中查询Excel工作表中的数据. 2007和2010版本: SELECT*FROMOp ...

  2. java通过jdbc连接数据库并更新数据(包括java.util.Date类型数据的更新)

    一.步骤 1.获取Date实例,并通过getTime()方法获得毫秒数: 2.将获取的毫秒数存储到数据库中,注意存储类型为nvarchar(20): 3.读取数据库的毫秒数,作为Date构造方法的参数 ...

  3. Java开发JDBC连接数据库

    Java开发JDBC连接数据库 创建一个以JDBC连接数据库的程序,包含6个步骤: JDBC五部曲1.加载驱动2.获得链接3.获取statement对象 4.执行SQL语句5.产生resultset对 ...

  4. 关于Java(JDBC连接数据库)

    Processing SQL Statements with JDBC 处理JDBC中的SQL语句 这节主要是 JDBC 与数据库交互的基本步骤 JDBC的基石是DriverManager,通过它,J ...

  5. log4j向oracle中插入一条系统当前时间的sql语句

    配置log4j,要向oracle插入一条系统当前时间的sql语句,按网上查找的总是出现各种各样的报错,最后总结出的写法是: ### shezhi### log4j.rootLogger = debug ...

  6. SQL反模式学习笔记18 减少SQL查询数据,避免使用一条SQL语句解决复杂问题

    目标:减少SQL查询数据,避免使用一条SQL语句解决复杂问题 反模式:视图使用一步操作,单个SQL语句解决复杂问题 使用一个查询来获得所有结果的最常见后果就是产生了一个笛卡尔积.导致查询性能降低. 如 ...

  7. 数据库函数:sqlite3_exec() SQL语句

    函数:sqlite3_exec(),称为便捷函数,封装了好多任务. 函数声明: int  sqlite3_exec( sqlite   * , const  char * sql , sqlite_c ...

  8. SQL Server高速导入数据分享

    SQL Server高速导入数据,能够尝试的方法例如以下:CTE.OpenRowSet/OpenDataSource.BULK INSERT.bcp.Shell. 以下依次介绍这几种办法. 1.CTE ...

  9. 使用Sql语句快速将数据表转换成实体类

    开发过程中经常需要根据数据表编写对应的实体类,下面是使用sql语句快速将数据表转换成对应实体类的代码,使用时只需要将第一行'TableName'引号里面的字母换成具体的表名称就行了: declare ...

随机推荐

  1. DOM设置css样式

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...

  2. 使用Java实现数据库编程-----------查询学生记录

    查询所有学生记录,包含年级名称 @Override public LIst<Student>getAllStudent() throws Exception{ List<Studen ...

  3. MAC OS系统替换homebrew使用阿里云的镜像源

    MAC OS系统替换homebrew使用阿里云的镜像源 2019-03-03 15:13:42 南通SEO 阅读数 2024更多 分类专栏: 解决方案   MAC OS系统替换homebrew使用阿里 ...

  4. scheduled定时任务+实例请求数据库

    1.scheduled定时任务类:ScheduledDemo.java package com.nantian.scheduled; import java.util.Date; import org ...

  5. mybatisplus构造器 condition

    不为null和不为“”的才会加入到sql语句中

  6. exam9.3

    #   用  户  名  公园 计划 抽卡   总分  19 859乔屹 100 03:15:05 40 03:14:01   140 03:15:05 emm 怎么讲 T2我把自己优化掉了40分 优 ...

  7. P2401 不等数列

    题目描述 将1到n任意排列,然后在排列的每两个数之间根据他们的大小关系插入“>”和“<”.问在所有排列中,有多少个排列恰好有k个“<”.答案对2015取模. 注:1~n的排列指的是1 ...

  8. P3478 [POI2008]STA-Station

    题目描述 The first stage of train system reform (that has been described in the problem Railways of the ...

  9. 【原创】go语言学习(十四)IO操作1

    目录: 格式化输入 格式化输出 终端输入输出背后的原理理 bufio包的使用 命令行参数处理理和urfave/cli使用 格式化输入 1.从终端获取⽤用户的输入 格式化输入 fmt.Scan(a …i ...

  10. [线性代数] 线性子空间入門 Basic Vector Subspaces

    导语:其他集数可在[线性代数]标籤文章找到.线性子空间是一个大课题,这里先提供一个简单的入门,承接先前关于矩阵代数的讨论,期待与你的交流. Overview: Subspace definition ...