---
title: "批处理+PreparedStatement 速度"
author: "DepthJava"
date: "2010-07-02T15:58:24Z"
tags: []
categories: ["编程语言"]
slug: "preparedstatement"
draft: false
lastmod: "2010-07-02T15:58:24Z"
id: 704494
url: "https://depthjava.iteye.com/blog/704494"
---

使用批处理功能涉及到两个方法：

addBatch(String)方法  
executeBatch方法  
addBatch方法可以接受一段标准的SQL（如果你使用一个Statement）作为参数，也可以什么参数都不带（如果你使用一个PreparedStatement）。  
executeBatch方法接着执行SQL语句，返回一个int型数组。这个数组包括每条语句影响到的行数。如果在一个批处理中使用是一个SELECT或者其它只返回结果的语句，那么将会产生一个SQLException异常

 

速度体验：

 1.使用：PrepareStatement 耗时16s

 

```
long t1=System.currentTimeMillis();
  String sql="insert into t1 values(?)";
   pre=conn.prepareStatement(sql);
  for(int i=0;i<100000;i++){
   pre.setObject(1, i);
   pre.executeUpdate();
  }  
  conn.commit();
  pre.close();
  conn.close(); 
  long t2=System.currentTimeMillis(); 
  System.out.println((t2-t1)/1000+"s");
```

 

 2.使用批处理 231 ms

 

```
  long t1=System.currentTimeMillis();  
  String sql = "insert into t1 values(?)";
  pre = conn.prepareStatement(sql);
  for(int i=1;i<=100000;i++){
     pre.setObject(1, i);
     pre.addBatch();   
    }
    pre.clearBatch();
    pre.executeBatch();  
    long t2=System.currentTimeMillis(); 
    System.out.println((t2-t1)+"s");
```

 

 

一般使用PrepareStatement+批处理 来处理大量数据！