此范例有兩個(gè)方法,create和createBatch。
批處理最主要的是效率提高,比一次次的處理數據所用的時(shí)間更短。
Java語(yǔ)言:
package cn.iego.wudi.jdbc;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class BatchTest {
public static void main(String[] args) throws Exception {
//處理100條數據
long start = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
create(i);
}
long end = System.currentTimeMillis();
System.out.println("creat:"+(end-start));
//100條數據批量處理
start = System.currentTimeMillis();
createBatch();
end = System.currentTimeMillis();
System.out.println("createBatch:"+(end-start));
}
//批處理
private static void createBatch() {
ResultSet rs = null;
Connection conn = null;
PreparedStatement ps =null;
String sql = "insert into user(name,birthday,money) values (?,?,?)";
try {
//jdbcUtils.getConnection()為自建工具類(lèi),用于獲得數據庫連接
conn = jdbcUtils.getConnection();
ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
//100條數據加入批處理
for (int j = 0; j < 100; j++) {
ps.setString(1, "batch name " + j);
ps.setDate(2, new Date(System.currentTimeMillis()));
ps.setFloat(3, 2000 + j);
ps.addBatch();
}
//執行批處理
ps.executeBatch();
} catch (Exception e) {
e.printStackTrace();
}
}
//普通處理
public static int create(int i) throws Exception{
ResultSet rs = null;
Connection conn = null;
PreparedStatement ps =null;
String sql = "insert into user(name,birthday,money) values (?,?,?)";
try {
conn = jdbcUtils.getConnection();
ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
ps.setString(1, "ps name "+i);
ps.setDate(2, new Date(System.currentTimeMillis()));
ps.setFloat(3, 2000+i);
ps.executeUpdate();
rs = ps.getGeneratedKeys();
if (rs.next()) {
return rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
}
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。