zoukankan      html  css  js  c++  java
  • 将JDBC查询出的数据转化为json格式返回

    使用JDBC,json工具使用的org.json

    /**
         * ResultSet转JSON
         *
         * @param rs
         * @return
         * @throws SQLException
         * @throws JSONException
         */
        public static JSONArray resultSetToJson(ResultSet rs) throws SQLException, JSONException, UnsupportedEncodingException {
            // json数组
            JSONArray array = new JSONArray();
            // 获取列数
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            // 遍历ResultSet中的每条数据
            while (rs.next()) {
                JSONObject jsonObj = new JSONObject();
                // 遍历每一列
                for (int i = 1; i <= columnCount; i++) {
                    String value = null;
                    String columnName = metaData.getColumnLabel(i);//列名称
                    if (rs.getString(columnName) != null && !rs.getString(columnName).equals("")) {
                        value = new String(rs.getBytes(columnName), "UTF-8");//列的值,有数据则转码
                        //  System.out.println("===" + value);
                    } else {
                        value = "";//列的值,为空,直接取出去
                    }
                    jsonObj.put(columnName, value);
                }
                array.add(jsonObj);
            }
            rs.close();
            return array;
        }
  • 相关阅读:
    kafka中配置细节
    kafka原理
    storm中的基本概念
    Spring装配Bean的过程补充
    Spring装配Bean的过程
    java中被遗忘的native关键字
    水塘抽样
    js常用总结
    HttpServletResponse status对应的状态信息
    mongoDB常用命令总结
  • 原文地址:https://www.cnblogs.com/hhhd/p/7473590.html
Copyright © 2011-2022 走看看