java sql批量提交

java sql批量提交

使用PreparedStatement批量提交SQL。
Connection conn  =   null ;
PreparedStatement pstmt 
=   null ;
try   {
    Class.forName(
"oracle.jdbc.driver.OracleDriver");
    conn 
= DriverManager.getConnection(
                    
"jdbc:oracle:thin:@localhost:1521:orcl""scott",
                    
"tigter");
    String sql 
= "delete from table_tmp where id = ?";
    conn.setAutoCommit(
false);
    pstmt 
=   conn.prepareStatement(sql);
    
for(int i = 100; i<200; i++{
        pstmt.setString(
1,i);
        pstmt.addBatch();
    }

    pstmt.executeBatch();
    conn.commite();
}
  catch (Exception e)  {
    e.printStackTrace();
}

finally   {
 
try {
    
if(pstmt != null)
                    pstmt.close();
            }
 catch (SQLException e) {
                e.printStackTrace();
            }

            
            
try {
                
if(conn != null{
                    conn.close();
                }

            }
  catch (SQLException e) {
                e.printStackTrace();
            }
}

finally

批量处理时效率比较高,只进行一次数据库连接。

你可能感兴趣的:(java sql批量提交)