pstm = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
设置为带返回ID
ResultSet rs = pstm.getGeneratedKeys();
通过rs.getInt(1)获得ID
下面为全部代码:
public static int executeUpdate(String sql, Object[] params){ Connection con = null; PreparedStatement pstm = null; try{ con = getCon(); pstm = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); if(params != null && params.length > 0){ for(int i = 0 ; i < params.length ; i++){ pstm.setObject(i+1, params[i]); } } int x = pstm.executeUpdate(); ResultSet rs = pstm.getGeneratedKeys(); if(rs.next()){ return rs.getInt(1); } return x; }catch(Exception e){ e.printStackTrace(); return -1; }finally{ close(null, pstm, con); } }