---
title: "如何用java jdbc 向数据库表插入大数据量"
author: "daoshud1"
date: "2013-11-26T17:17:24Z"
tags: []
categories: ["编程语言"]
slug: "java-jdbc"
draft: false
lastmod: "2014-06-05T16:20:40Z"
id: 1981059
url: "https://daoshud1.iteye.com/blog/1981059"
---

jvm：-Xmx1024m
size = 1000000，可以插入成功。

如果再为size增大一个数量级，还是OutOfMemoryError，这时内存已经不好再增加分配了
批量处理本来是为了提高性能，但是太大的数据提交，因为堆的膨胀，堆的寻址会造成性能反而下降。
PreparedStatement加executeBatch方法可以更快，主要想提高预编译sql文件的次数，从而达到提高效率。
如果是为了事务处理，不妨用个变通的办法，建立临时表，导入数据，还是可以用到addBatch，比如每100条一个批次。

然后在另外一张表有个记录，记录是否全部导入成功的标志。

基本思路是利用两段提交理论
------------------------------

```java

public class App {
public static void main(String[] args) throws Exception {
Connection connection = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:XE", "marshal", "password");
PreparedStatement preparedStatement = connection
.prepareStatement("insert into addbatch_test(id,name) values(?,?)");

int size = 1000000;

for (int i = 0; i < size; i++) {
preparedStatement.setInt(1, i);
preparedStatement.setString(2, "n" + i);
preparedStatement.addBatch();
}

preparedStatement.executeBatch();

preparedStatement.close();
connection.close();
}
}

```