將JDBC查詢出的數據轉化爲json格式返回

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

/**
     * 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;
    }
相關文章
相關標籤/搜索