前処理PreparedSttementを使ってSql文を実行します.

4365 ワード

/**

     *           Sql

     * @param sql Sql  

     * @param obj      

     * @return     

     * @throws SQLException

     */

    public List<Map<String, Object>> query(String sql, Object[] obj) throws SQLException

    {

        List<Map<String, Object>> ret = null;

        PreparedStatement ps = null;

        ResultSet rs = null;

        try {

            log.debug("start sql="+sql);

            ps = conn.prepareStatement(sql);

            if(obj != null && obj.length > 0){

                for (int i = 0, len = obj.length; i < len; i++) {

                    ps.setObject(i + 1, obj[i]);

                    log.debug("parameterValue: " + obj[i]);

                }

            }

            rs = ps.executeQuery();

            ResultSetMetaData rmd = rs.getMetaData();

            ret = new ArrayList<Map<String,Object>>();

            while (rs.next()) {

                Map<String, Object> rowMap = new LinkedHashMap<String, Object>();

                for (int i = 1, count = rmd.getColumnCount() + 1; i < count; i++) {

                    rowMap.put(rmd.getColumnName(i), rs.getObject(i));

                }

                ret.add(rowMap);

            }

        } catch (SQLException e) {

            log.debug("  sql    ,sql: " + sql + "," + e.getMessage());

            throw e;

        } finally {

            if (rs != null) {

                try {

                    rs.close();

                } catch (SQLException e) {

                    e.printStackTrace();

                }

            }

            if (ps != null) {

                try {

                    ps.close();

                } catch (SQLException e) {

                    e.printStackTrace();

                }

            }

        }

        return ret;

    }