日期:2014-05-16 浏览次数:20743 次
/** * 执行插入操作并且获得新的Id * * @param dataSource * @param sql * @param params * @return * @throws SQLException */ public static int insertAndGetId(DataSource dataSource, String sql, Object[] params) throws SQLException { Connection con = dataSource.getConnection(); PreparedStatement pstmt = con.prepareStatement(sql); try { for (int i = 1; i <= params.length; i++) { pstmt.setObject(i, params[i - 1]); } pstmt.executeUpdate(); ResultSet rs = pstmt.executeQuery("SELECT LAST_INSERT_ID()"); rs.next(); int newId = rs.getInt(1); rs.close(); return newId; } finally { try { pstmt.close(); } finally { con.close(); } } }