PreparedStatement IN clause alternatives?

前端 未结 30 3998
情歌与酒
情歌与酒 2020-11-21 05:19

What are the best workarounds for using a SQL IN clause with instances of java.sql.PreparedStatement, which is not supported for multiple values du

30条回答
  •  我寻月下人不归
    2020-11-21 05:33

    My example for SQLite and Oracle databases.

    The first For loop is for Creating a PreparedStatement Objects.

    The second For loop is for Supplying Values for PreparedStatement Parameters.

    List roles = Arrays.asList("role1","role2","role3");
    Map menu = getMenu(conn, roles);
    

    public static Map getMenu(Connection conn, List roles ) {
        Map menu = new LinkedHashMap();
    
        PreparedStatement stmt;
        ResultSet rset;
        String sql;
        try {
            if (roles == null) {
                throw new Exception();
            }
            int size = roles.size();
            if (size == 0) {
                throw new Exception("empty list");
            }
            StringBuilder sb = new StringBuilder();
            sb.append("select page_controller, page_name from pages "
                    + " where page_controller in (");
            for (int i = 0; i < size; i++) {
                sb.append("?,");
            }
            sb.setLength(sb.length() - 1);
            sb.append(") order by page_id");
            sql = sb.toString();
            stmt = conn.prepareStatement(sql);
            for (int i = 0; i < size; i++) {
                stmt.setString(i + 1, roles.get(i));
            }
            rset = stmt.executeQuery();
            while (rset.next()) {
                menu.put(rset.getString(1), rset.getString(2));
            }
    
            conn.close();
        } catch (Exception ex) {
            logger.info(ex.toString());
            try {
                conn.close();
            } catch (SQLException e) {
            }
            return menu;
        }
        return menu;
    }
    

提交回复
热议问题