首页 > 代码库 > 使用预处理PreparedStatement执行Sql语句

使用预处理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;    }

 

使用预处理PreparedStatement执行Sql语句