使用预处理PreparedStatement执行Sql语句

/**
     * 使用预处理的方式执行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;
    }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。