日期:2014-05-16 浏览次数:20514 次
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.HashMap; import java.util.List; public class TestPs{ //**数据库配置******************************** String ORACLE_URL = "jdbc:oracle:thin:@localhost:1521:orcl"; String ORACLE_USERNAME = "test"; String ORACLE_PASSWORD = "test"; public void excute(){ List<HashMap> list = query();//取得列表的方法,略。 //处理数据 Class.forName("oracle.jdbc.driver.OracleDriver"); Connection conn = DriverManager.getConnection(ORACLE_URL, ORACLE_USERNAME, ORACLE_PASSWORD); try{ conn.setAutoCommit(false); //设置不会自动提交 PreparedStatement ps = conn.prepareStatement("insert into TESTTABLE values (?, ?, ?)"); for(int i = 0;i<list.size();i++){ HashMap map = list.get(i); ps.setString(1, map.get("id").toString()); ps.setString(2, map.get("name").toString()); ps.setString(3, map.get("age").toString()); ps.addBatch(); } ps.executeBatch();//执行批量插入 ps.close(); conn.commit(); //提交事务 conn.close(); }catch(Exception e){ try{ conn.rollback(); // 操作不成功,回滚事务 }catch(SQLException r){ System.out.println("回滚事务出错!" + r.getMessage()); } System.out.println(e.getMessage()); } conn.close(); } }