批处理可明显的提高程序读写的效率.下面是个简单示例.
package batch;
import dbpool.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;
import java.sql.*;
public class BatchInsert {
public static void main(String[] args){
// TODO Auto-generated method stub
try {
sybaseDB();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("asdfasdfasfasf");
}
public static void sybaseDB()throws SQLException
{
Class.forName("com.sybase.jdbc2.jdbc.SybDriver");
//url连接字符串Ip后的是端口号/comoa是数据库名
String url =" jdbc:sybase:Tds:192.168.12.5:5000/comoa";
java.util.Properties sysProps = System.getProperties();
sysProps.put("user","comoa");
sysProps.put("password","123456");
//建立数据库连接
Connection conn= DriverManager.getConnection(url, sysProps);
String sql = "INSERT INTO TAB_TABLE2(NAME,AGE) VALUES (?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
final int batchSize = 1000;
int count = 0;
do{
ps.setString(1, "a"+count);
ps.setInt(2, count);
ps.addBatch();
if(++count % batchSize == 0) {
ps.executeBatch();
}
}while(count<10000);
ps.executeBatch(); // insert remaining records
ps.close();
connection.close();
}
}
这是当1000条数据时添加向数据库,共添加了10000条数据.