使用預處理PreparedStatement執行Sql語句

qingyezhu發表於2014-11-06
/**
     * 使用預處理的方式執行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;
    }

 

相關文章