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;
        }
  • 相关阅读:
    开机自动挂载分区
    Wine安装
    ubuntu 将idea/vscode快捷方式加入到启动器中
    在Linux上安装Java
    httpclient
    shiro
    redis-随笔
    maven
    spring的aop
    spring事务知识梳理
  • 原文地址:https://www.cnblogs.com/hhhd/p/7473590.html
Copyright © 2011-2022 走看看