首页 > 技术文章 > Java:批量插入、修改数据到数据库中的用法

tashaxing 2018-07-03 14:26 原文

在java中使用JDBC实现批处理的对象一般是使用PrepareStatement对象

 

批量插入:

 1 Class.forName("Oracle.jdbc.driver.OracleDriver");
 2 Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:demo" , "scott" , "tiger");
 3 PreparedStatement ps = conn.prepareStatement("insert into dept2 values(? , ? , ?)");
 4 
 5 for(Dept dept-> depts){
 6         ps.setInt(1, dept.Id);
 7         ps.setString(2, dept.Name);
 8         ps.setString(3, dept.Description);
 9         ps.addBatch();
10 }
11 
12 ps.executeBatch();
13 ps.close();
14 
15 conn.close();

批量更新:

 1 Class.forName("Oracle.jdbc.driver.OracleDriver");
 2 Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:demo" , "scott" , "tiger");
 3 PreparedStatement ps = conn.prepareStatement("insert into dept2 values(? , ? , ?)");
 4 
 5 for(Dept dept-> depts){
 6         ps.setInt(1, dept.Id);
 7         ps.setString(2, dept.Name);
 8         ps.setString(3, dept.Description);
 9         ps.addBatch();
10 }
11 
12 ps.executeBatch();
13 ps.close();
14 
15 conn.close();

 

推荐阅读