jdbc oracle 批量更新 Statement中addBatch方法

在批量更新 SQL 操作的时候建议使用 Statement 接口里的addBatch,这样效率是高些,数据量越大越能体现出来

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/*
 * 批量更新Statement中addBatch方法
 * */
public class addBatch{
    public static void main(String[] args) {
        String url = "jdbc:oracle:thin:@localhost:1521:orcl";
        String user = "caj";
        String password = "123456";
        Connection con = null;
        java.sql.Statement st = null;           
        try {
            Class.forName("oracle.jdbc.OracleDriver");
            con = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

            try {
                con.setAutoCommit(false);
                st = con.createStatement();

                st.addBatch("insert into temp(eno,ename,mytime) values('43','sun59',to_date('1982/03/23','yyyy/mm/dd'))");
                st.addBatch("insert into temp(eno,ename,mytime) values('42','sun60',to_date('1982/03/23','yyyy/mm/dd'))");
                //st.addBatch("insert into temp(eno,ename,mytime) values('7948','sun9','1982-03-23')");//该句文字与格式字符串不匹配 回滚 不执行更新
                st.addBatch("insert into temp(eno,ename,mytime) values('44','sun10',to_date('1982/03/23','yyyy/mm/dd'))");
                st.addBatch("insert into temp(eno,ename,mytime) values('45','sun11',to_date('1982/03/23','yyyy/mm/dd'))");
                st.executeBatch();
                con.commit();
            } catch (SQLException e) {
                System.out.println("=========");                 
                try {
                    con.rollback();
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }   
    }
}

你可能感兴趣的:(java)