JDBC的批处理操作三种方式 pstmt.addBatch();

SQL批处理是JDBC性能优化的重要武器,经本人研究总结,批处理的用法有三种。

package lavasoft.jdbctest;

import lavasoft.common.DBToolkit;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

/**
* JDBC的批量操作三种方式
*/
public class BatchExeSQLTest {

        public static void main(String[] args) {
                exeBatchStaticSQL();
        }

        /**
         * 批量执行预定义模式的SQL
         */
        public static void exeBatchParparedSQL() {
                Connection conn = null;
                try {
                        conn = DBToolkit.getConnection();
                        String sql = "insert into testdb.book (kind, name) values (?,?)";
                        PreparedStatement pstmt = conn.prepareStatement(sql);
                        pstmt.setString(1, "java");
                        pstmt.setString(2, "jjjj");
                        pstmt.addBatch();                     //添加一次预定义参数
                        pstmt.setString(1, "ccc");
                        pstmt.setString(2, "dddd");
                        pstmt.addBatch();                     //再添加一次预定义参数
                        //批量执行预定义SQL
                        pstmt.executeBatch();
                } catch (SQLException e) {
                        e.printStackTrace();
                } finally {
                        DBToolkit.closeConnection(conn);
                }
        }

        /**
         * 批量执行混合模式的SQL、有预定义的,还有静态的
         */
        public static void exeBatchMixedSQL() {
                Connection conn = null;
                try {
                        conn = DBToolkit.getConnection();
                        String sql = "insert into testdb.book (kind, name) values (?,?)";
                        PreparedStatement pstmt = conn.prepareStatement(sql);
                        pstmt.setString(1, "java");
                        pstmt.setString(2, "jjjj");
                        pstmt.addBatch();    //添加一次预定义参数
                        pstmt.setString(1, "ccc");
                        pstmt.setString(2, "dddd");
                        pstmt.addBatch();    //再添加一次预定义参数
                        //添加一次静态SQL
                        pstmt.addBatch("update testdb.book set kind = 'JAVA' where kind='java'");
                        //批量执行预定义SQL
                        pstmt.executeBatch();
                } catch (SQLException e) {
                        e.printStackTrace();
                } finally {
                        DBToolkit.closeConnection(conn);
                }
        }

        /**
         * 执行批量静态的SQL
         */
        public static void exeBatchStaticSQL() {
                Connection conn = null;
                try {
                        conn = DBToolkit.getConnection();
                        Statement stmt = conn.createStatement();
                        //连续添加多条静态SQL
                        stmt.addBatch("insert into testdb.book (kind, name) values ('java', 'java in aciton')");
                        stmt.addBatch("insert into testdb.book (kind, name) values ('c', 'c in aciton')");
                        stmt.addBatch("delete from testdb.book where kind ='C#'");
                        stmt.addBatch("update testdb.book set kind = 'JAVA' where kind='java'");
//                        stmt.addBatch("select count(*) from testdb.book");                //批量执行不支持Select语句
                        //执行批量执行
                        stmt.executeBatch();
                } catch (SQLException e) {
                        e.printStackTrace();
                } finally {
                        DBToolkit.closeConnection(conn);
                }
        }
}

注意:JDBC的批处理不能加入select语句,否则会抛异常:
java.sql.BatchUpdateException: Can not issue SELECT via executeUpdate().
  at com.mysql.jdbc.StatementImpl.executeBatch(StatementImpl.java:1007)

转载自:http://lavasoft.blog.51cto.com/62575/238651











批量更新,插入代码
1./**  
2. * 更新数据库已有的customer信息  
3. * @param List<CustomerBean>  
4. * @return   
5. */  
6.public int updateExistsInfo(List<CustomerBean> updateList){  
7.      
8.    //查询的SQL语句  
9.    String sql = "update t_customer set LICENSE_KEY=?,CORPORATE_NAME=?,INTEGRATED_CLASSIFICATION=?,BOSSHEAD=?," +  
10.            "CONTACT_PHONE=?,ORDER_FREQUENCY=?,CONTACT_ADDRESS=?,USER_ID=? where CUSTOMER_ID=?" ;  
11.      
12.    //插入需要的数据库对象  
13.    Connection conn = null;  
14.    PreparedStatement pstmt = null;  
15. 
16.    try  {            
17.        conn = new DBSource().getConnection();  
18. 
19.        //设置事务属性  
20.        conn.setAutoCommit(false);  
21.          
22.        pstmt = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);              
23. 
24.        for(CustomerBean cbean : updateList){  
25.            pstmt.setString(1, cbean.getLicense_key());  
26.            pstmt.setString(2, cbean.getCorporate_name());  
27.            pstmt.setString(3, cbean.getIntegrated_classification());  
28.            pstmt.setString(4, cbean.getBosshead());  
29.            pstmt.setString(5, cbean.getContact_phone());  
30.            pstmt.setString(6, cbean.getOrder_frequency());  
31.            pstmt.setString(7, cbean.getContact_address());  
32.            pstmt.setInt   (8, cbean.getUser_id());  
33.            pstmt.setInt   (9, cbean.getCustomer_id());  
34.              
35.            pstmt.addBatch();  
36.              
37.        }  
38.        int[] tt = pstmt.executeBatch();  
39.        System.out.println("update : " + tt.length);  
40. 
41.        //提交,设置事务初始值  
42.        conn.commit();  
43.        conn.setAutoCommit(true);  
44. 
45.        //插入成功,返回  
46.        return tt.length;  
47. 
48.    }catch(SQLException ex){  
49.        try{  
50.            //提交失败,执行回滚操作  
51.            conn.rollback();  
52. 
53.        }catch (SQLException e) {  
54.            e.printStackTrace();  
55.            System.err.println("updateExistsInfo回滚执行失败!!!");  
56.        }  
57. 
58.        ex.printStackTrace();  
59.        System.err.println("updateExistsInfo执行失败");  
60. 
61.        //插入失败返回标志0 
62.        return 0;  
63. 
64.    }finally {  
65.        try{  
66.            //关闭资源  
67.            if(pstmt != null)pstmt.close();  
68.            if(conn != null)conn.close();  
69.              
70.        }catch (SQLException e) {  
71.            e.printStackTrace();  
72.            System.err.println("资源关闭失败!!!");  
73.        }  
74.    }  
75.}   
76. 
77./**  
78. * 插入数据中没有的customer信息  
79. * @param List<CustomerBean>  
80. * @return   
81. */  
82.public int insertNewInfo(List<CustomerBean> insertList){  
83.              
84.    //查询的SQL语句  
85.    String sql = "insert into t_customer(CUSTOMER_ID," +  
86.            "LICENSE_KEY,CORPORATE_NAME,INTEGRATED_CLASSIFICATION,BOSSHEAD,CONTACT_PHONE," +  
87.            "ORDER_FREQUENCY,CONTACT_ADDRESS,USER_ID,CUSTOMER_NUM,CUSTOMER_CODING," +  
88.            "INVESTIGATION_TIME,SMS_REC_FLAG,WAP_FLAG,PRICE_GATHERING_FLAG,SOCIETY_STOCK_FLAG," +  
89.            "REGION_TYPE)" +  
90.            "VALUES(CUSTOMER.NEXTVAL," +  
91.            "?,?,?,?,?," +  
92.            "?,?,?,?,?," +  
93.            "TO_DATE(?,'YYYY-MM-DD'),?,0,0,0," +  
94.            "?)" ;  
95.      
96.    //插入需要的数据库对象  
97.    Connection conn = null;  
98.    PreparedStatement pstmt = null;  
99. 
100.    try  {            
101.        conn = new DBSource().getConnection();  
102. 
103.        //设置事务属性  
104.        conn.setAutoCommit(false);  
105.          
106.        pstmt = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);              
107. 
108.        for(CustomerBean cbean : insertList){  
109.            pstmt.setString(1, cbean.getLicense_key());  
110.            pstmt.setString(2, cbean.getCorporate_name());  
111.            pstmt.setString(3, cbean.getIntegrated_classification());  
112.            pstmt.setString(4, cbean.getBosshead());  
113.            pstmt.setString(5, cbean.getContact_phone());  
114.            pstmt.setString(6, cbean.getOrder_frequency());  
115.            pstmt.setString(7, cbean.getContact_address());  
116.            pstmt.setInt(8, cbean.getUser_id());  
117.            pstmt.setString(9, "gyyc00000");//  
118.            pstmt.setString(10, "95000000");//  
119.            pstmt.setString(11, getToday());  
120.            pstmt.setInt(12, cbean.getSms_rec_flag());  
121.            pstmt.setInt(13, cbean.getRegion_type());  
122.              
123. 
124.            pstmt.addBatch();  
125. 
126.        }  
127.        int[] tt = pstmt.executeBatch();  
128.        System.out.println("insert : " + tt.length);  
129. 
130.        //提交,设置事务初始值  
131.        conn.commit();  
132.        conn.setAutoCommit(true);  
133. 
134.        //插入成功,返回  
135.        return tt.length;  
136. 
137.    }catch(SQLException ex){  
138.        try{  
139.            //提交失败,执行回滚操作  
140.            conn.rollback();  
141. 
142.        }catch (SQLException e) {  
143.            e.printStackTrace();  
144.            System.err.println("insertNewInfo回滚执行失败!!!");  
145.        }  
146. 
147.        ex.printStackTrace();  
148.        System.err.println("insertNewInfo执行失败");  
149. 
150.        //插入失败返回标志0 
151.        return 0;  
152. 
153.    }finally {  
154.        try{  
155.            //关闭资源  
156.            if(pstmt != null)pstmt.close();  
157.            if(conn != null)conn.close();  
158.              
159.        }catch (SQLException e) {  
160.            e.printStackTrace();  
161.            System.err.println("资源关闭失败!!!");  
162.        }  
163.    }  
164.}   
/**
* 更新数据库已有的customer信息
* @param List<CustomerBean>
* @return
*/
public int updateExistsInfo(List<CustomerBean> updateList){

//查询的SQL语句
String sql = "update t_customer set LICENSE_KEY=?,CORPORATE_NAME=?,INTEGRATED_CLASSIFICATION=?,BOSSHEAD=?," +
"CONTACT_PHONE=?,ORDER_FREQUENCY=?,CONTACT_ADDRESS=?,USER_ID=? where CUSTOMER_ID=?" ;

//插入需要的数据库对象
Connection conn = null;
PreparedStatement pstmt = null;

try  {
conn = new DBSource().getConnection();

//设置事务属性
conn.setAutoCommit(false);

pstmt = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

for(CustomerBean cbean : updateList){
pstmt.setString(1, cbean.getLicense_key());
pstmt.setString(2, cbean.getCorporate_name());
pstmt.setString(3, cbean.getIntegrated_classification());
pstmt.setString(4, cbean.getBosshead());
pstmt.setString(5, cbean.getContact_phone());
pstmt.setString(6, cbean.getOrder_frequency());
pstmt.setString(7, cbean.getContact_address());
pstmt.setInt   (8, cbean.getUser_id());
pstmt.setInt   (9, cbean.getCustomer_id());

pstmt.addBatch();

}
int[] tt = pstmt.executeBatch();
System.out.println("update : " + tt.length);

//提交,设置事务初始值
conn.commit();
conn.setAutoCommit(true);

//插入成功,返回
return tt.length;

}catch(SQLException ex){
try{
//提交失败,执行回滚操作
conn.rollback();

}catch (SQLException e) {
e.printStackTrace();
System.err.println("updateExistsInfo回滚执行失败!!!");
}

ex.printStackTrace();
System.err.println("updateExistsInfo执行失败");

//插入失败返回标志0
return 0;

}finally {
try{
//关闭资源
if(pstmt != null)pstmt.close();
if(conn != null)conn.close();

}catch (SQLException e) {
e.printStackTrace();
System.err.println("资源关闭失败!!!");
}
}
}

/**
* 插入数据中没有的customer信息
* @param List<CustomerBean>
* @return
*/
public int insertNewInfo(List<CustomerBean> insertList){

//查询的SQL语句
String sql = "insert into t_customer(CUSTOMER_ID," +
"LICENSE_KEY,CORPORATE_NAME,INTEGRATED_CLASSIFICATION,BOSSHEAD,CONTACT_PHONE," +
"ORDER_FREQUENCY,CONTACT_ADDRESS,USER_ID,CUSTOMER_NUM,CUSTOMER_CODING," +
"INVESTIGATION_TIME,SMS_REC_FLAG,WAP_FLAG,PRICE_GATHERING_FLAG,SOCIETY_STOCK_FLAG," +
"REGION_TYPE)" +
"VALUES(CUSTOMER.NEXTVAL," +
"?,?,?,?,?," +
"?,?,?,?,?," +
"TO_DATE(?,'YYYY-MM-DD'),?,0,0,0," +
"?)" ;

//插入需要的数据库对象
Connection conn = null;
PreparedStatement pstmt = null;

try  {
conn = new DBSource().getConnection();

//设置事务属性
conn.setAutoCommit(false);

pstmt = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

for(CustomerBean cbean : insertList){
pstmt.setString(1, cbean.getLicense_key());
pstmt.setString(2, cbean.getCorporate_name());
pstmt.setString(3, cbean.getIntegrated_classification());
pstmt.setString(4, cbean.getBosshead());
pstmt.setString(5, cbean.getContact_phone());
pstmt.setString(6, cbean.getOrder_frequency());
pstmt.setString(7, cbean.getContact_address());
pstmt.setInt(8, cbean.getUser_id());
pstmt.setString(9, "gyyc00000");//
pstmt.setString(10, "95000000");//
pstmt.setString(11, getToday());
pstmt.setInt(12, cbean.getSms_rec_flag());
pstmt.setInt(13, cbean.getRegion_type());


pstmt.addBatch();

}
int[] tt = pstmt.executeBatch();
System.out.println("insert : " + tt.length);

//提交,设置事务初始值
conn.commit();
conn.setAutoCommit(true);

//插入成功,返回
return tt.length;

}catch(SQLException ex){
try{
//提交失败,执行回滚操作
conn.rollback();

}catch (SQLException e) {
e.printStackTrace();
System.err.println("insertNewInfo回滚执行失败!!!");
}

ex.printStackTrace();
System.err.println("insertNewInfo执行失败");

//插入失败返回标志0
return 0;

}finally {
try{
//关闭资源
if(pstmt != null)pstmt.close();
if(conn != null)conn.close();

}catch (SQLException e) {
e.printStackTrace();
System.err.println("资源关闭失败!!!");
}
}
}


Notice:

//设置事务属性
conn.setAutoCommit(false);

pstmt = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

for(CustomerBean cbean : updateList){
pstmt.setString(1, cbean.getLicense_key());
...   
    pstmt.addBatch();

}
int[] tt = pstmt.executeBatch();
System.out.println("update : " + tt.length);

//提交,设置事务初始值
conn.commit();
conn.setAutoCommit(true);
...

你可能感兴趣的:(sql,mysql,jdbc,Blog,WAP)