此范例有兩個(gè)方法,create和createBatch。
批處理最主要的是效率提高,比一次次的處理數(shù)據(jù)所用的時(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條數(shù)據(jù)
long start = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
create(i);
}
long end = System.currentTimeMillis();
System.out.println("creat:"+(end-start));
//100條數(shù)據(jù)批量處理
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()為自建工具類,用于獲得數(shù)據(jù)庫(kù)連接
conn = jdbcUtils.getConnection();
ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
//100條數(shù)據(jù)加入批處理
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();
}
//執(zhí)行批處理
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;
}
}
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。