当前位置: 代码迷 >> J2SE >> 批量更新的有关问题
  详细解决方案

批量更新的有关问题

热度:55   发布时间:2016-04-24 00:28:15.0
批量更新的问题
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的参数不同
  相关解决方案