package cn.itcast.jdbc; import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class BatchTest { public static void main(String[] args) throws SQLException {
/*for (int i = 0; i < 1000; i++) {
create(i);
}*/
createBatch();
} static int create(int i) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null; try {
conn = jdbcUtils.getConnection(); String sql = "insert into user(name,birthday,money) values(?,?,?)"; ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(, "name" + i);
ps.setDate(, (java.sql.Date) new Date(System.currentTimeMillis()));
ps.setFloat(, 1000F + i); ps.executeUpdate(); rs = ps.getGeneratedKeys();
int id = ; if (rs.next())
id = rs.getInt(); return id; } finally {
jdbcUtils.free(rs, ps, conn);
}
} static void createBatch() throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null; try {
conn = jdbcUtils.getConnection(); String sql = "insert into user(name,birthday,money) values(?,?,?)"; ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); for (int i = ; i < ; i++) {
ps.setString(, "name" + i);
ps.setDate(, new Date(System.currentTimeMillis()));
ps.setFloat(, 1000F + i); ps.addBatch();
} int[] is = ps.executeBatch(); } finally {
jdbcUtils.free(rs, ps, conn);
}
} }
BatchTest