java中批量執(zhí)行JDBC操作時(shí)如果要批量插入數(shù)據(jù)的話,用 addBatch()用法很方便,具體用法下例:
- sql = "INSERT INTO LOG_FILENAME(ID,FILENAME,CREATETIME) VALUES(2,?,sysdate)";
-
- public void batchInsertFileNames(File[] files) throws SQLException {
- Connection conn = null;
- PreparedStatement pstmt = null;
- try {
- conn = dataSource.getConnection();
- pstmt = (PreparedStatement) conn.prepareStatement(sql);
- Date date = new Date();
- for (int i = 0; i < files.length; i++) {
- setParams(pstmt, files[i].getName(), date);
- }
- //下句執(zhí)行后開(kāi)始批量插入數(shù)據(jù)
- pstmt.executeBatch();
- } finally {
- DbUtils.close(pstmt);
- }
- }
-
- private void setParams(PreparedStatement pstmt, String fileName, Date date)
- throws SQLException {
- pstmt.setString(1, fileName);
- //addBatch();執(zhí)行后暫時(shí)記錄此條插入
- pstmt.addBatch();
- }