日期:2014-05-20  浏览次数:20939 次

批量更新的问题
Java code

public int BatchUpdate(String[] fields, String tableName, String[] conditions,String id) {
        Connection conn = null; 
        PreparedStatement pst = null;
        int count=0;
        String sql="";
        try {
            conn = ConnectionSource.getConnection();
            conn.setAutoCommit(false);
        for(int i=0;i<conditions.length;i++){
        sql="update  "+tableName +" set "+fields[i]+" where "+id+"=?";
        pst = conn.prepareStatement(sql);
        pst.setObject(1, conditions[i]);   
        pst.addBatch();
        }
            
        int[]s=    pst.executeBatch();
             conn.commit();
             count=s.length;
        } catch (SQLException e) {
            if(conn != null){
                try {
                    conn.rollback();
                    conn.commit();
                } catch (SQLException e1) {
                    loggerError.error(sql);
                    loggerError.error(e1);
                    e1.printStackTrace();
                }    
            }
            loggerError.error(e);
            e.printStackTrace();
        } finally {
            ConnectionSource.releaseSource(null, pst, conn);
        }
        return count;
    }


我不明白为什么只能更新最后一条记录,到底问题出在哪里看不出来,请大家帮忙看看。。谢谢了

------解决方案--------------------
你这种没法用PreparedStatment的addBatch来做
PreparedStatment#addBatch的前提是语句是一样的,只是set的参数不同