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;
        }
  • 相关阅读:
    linux终端发送邮件
    ubuntu交换Caps 和 ESC
    pycharm快捷键
    python catch socket timeout
    pgsql restart
    python re.sub
    文件写入与缓存
    HTTP协议再分析
    leetcode-45
    Java的锁
  • 原文地址:https://www.cnblogs.com/hhhd/p/7473590.html
Copyright © 2011-2022 走看看