Pass ResultSet to a JSON in Java JSP

2

My query is to know how I can pass a ResultSet from SQLServer to JSON, since I am working with JavaScript libraries (ChartJS) to generate graphics for a dashboard and it only reads data in that format.

package DAO;

import conexion.Conexion;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.json.JSONObject;

public class GraficaDAO {

    private static final Conexion con = Conexion.conectar();
    private static PreparedStatement ps = null;
    private static ResultSet res = null;

    public ResultSet reporteMensual(String mes) throws Exception {

        String sproc = "{call sp_EquiposMes (?)}";

        try {
            ps = con.getCnn().prepareCall(sproc);
            ps.setString(1, mes.toString());
            res = ps.executeQuery();

            while (res.next()){
                String equipos = res.getString(1);
            }

        } catch (SQLException ex) {

        } finally {
            try {
                if (res != null) {
                    res.close();
                }
                if (ps != null) {
                    ps.close();
                }
                con.cerrarConexion();
            } catch (Exception e) {
            }
        }
        return res;
    }
}

That is the code of my query, for the moment I was storing it in a String to corroborate if the data arrives.

    
asked by Wil Pedroso 07.01.2017 в 01:09
source

2 answers

1

When you work with your database layer, instead of returning a ResultSet , it is best to return an object or representation of the data you want to work with, then you can transform that data as you see fit.

In the case of your GraficaDAO#reporteMensual method, the best thing you can do is get the data returned by the stored procedure in a list and then convert this list to a JSON object (or whatever else you need).

public class GraficaDAO {

    private static final String sproc = "{call sp_EquiposMes (?)}";

    //devuelve una lista, no el ResultSet
    //una vez que cierres la conexión a base de datos, el ResultSet
    //estará cerrado y no podrá ser usado
    public List<ResultadosGrafico> reporteMensual(String mes) {
        List<ResultadosGrafico> lista = new ArrayList<>();

        //todos los elementos de conexion a base de datos deben estar
        //en el menor alcance posible para el metodo
        Conexion con = Conexion.conectar();
        //siempre dentro de un bloque try con recursos
        //automáticamente llamará al método close de los
        //recursos abiertos dentro de los "parámetros" del try
        //disponible desde Java 7
        try (Connection conn = con.getCnn();
            //para invocar procedimientos almacenados en Java
            //conviene usar CallableStatement
            CallableStatement cs = conn.prepareCall(sproc);) {
            //mes ya es un String, no tienes que llamar a su método toString
            cs.setString(1, mes);
            try (ResultSet res = cs.executeQuery()) {
                while (res.next()) {
                    //parsea el resultado de cada fila del ResultSet
                    ResultadosGrafico rg = new ResultadosGrafico();
                    //en lugar de usar el número de columna, mejor usa el nombre de la columna que se ha devuelto
                    rg.setAtributo1(res.getString("columna1"));
                    rg.setAtributo2(res.getString("columna2"));
                    //etc...

                    //importante: agregar este elemento en tu lista
                    lista.add(rg);
                }
            }
        } catch (SQLException ex) {
            //por lo menos debes loguear esta excepción
            ex.printStackTrace();
        }
    }
    return lista;
}

Then, you can use a library like JSON.org to convert the List<ResultadosGrafico> list to a JSON string. But this is too much work. It is best to use libraries like jackson or Google gson that make the conversion simpler and easier to maintain.

Following the previous design and with a library like jackson, you can do as follows:

public class ClienteReporteGrafico {

    public static void main(String[] args) throws Exception {
        //obtener la lista desde el dao
        GraficaDAO graficaDAO = new GraficaDAO();
        List<ResultadosGrafico> lista = graficaDAO.reporte();
        //jackson convierte tu objeto en json
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(lista);
        //pintamos el json en la consola para ver el resultado
        System.out.println(json);
    }
}
    
answered by 07.01.2017 / 16:36
source
1

You can use the following code to create a json object and then add each element of the resultset to the json.

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;

import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

public class ResultSetConverter {
  public static JSONArray convert( ResultSet rs )
    throws SQLException, JSONException
  {
    JSONArray json = new JSONArray();
    ResultSetMetaData rsmd = rs.getMetaData();

    while(rs.next()) {
      int numColumns = rsmd.getColumnCount();
      JSONObject obj = new JSONObject();

      for (int i=1; i<numColumns+1; i++) {
        String column_name = rsmd.getColumnName(i);

        if(rsmd.getColumnType(i)==java.sql.Types.ARRAY){
         obj.put(column_name, rs.getArray(column_name));
        }
        else if(rsmd.getColumnType(i)==java.sql.Types.BIGINT){
         obj.put(column_name, rs.getInt(column_name));
        }
        else if(rsmd.getColumnType(i)==java.sql.Types.BOOLEAN){
         obj.put(column_name, rs.getBoolean(column_name));
        }
        else if(rsmd.getColumnType(i)==java.sql.Types.BLOB){
         obj.put(column_name, rs.getBlob(column_name));
        }
        else if(rsmd.getColumnType(i)==java.sql.Types.DOUBLE){
         obj.put(column_name, rs.getDouble(column_name)); 
        }
        else if(rsmd.getColumnType(i)==java.sql.Types.FLOAT){
         obj.put(column_name, rs.getFloat(column_name));
        }
        else if(rsmd.getColumnType(i)==java.sql.Types.INTEGER){
         obj.put(column_name, rs.getInt(column_name));
        }
        else if(rsmd.getColumnType(i)==java.sql.Types.NVARCHAR){
         obj.put(column_name, rs.getNString(column_name));
        }
        else if(rsmd.getColumnType(i)==java.sql.Types.VARCHAR){
         obj.put(column_name, rs.getString(column_name));
        }
        else if(rsmd.getColumnType(i)==java.sql.Types.TINYINT){
         obj.put(column_name, rs.getInt(column_name));
        }
        else if(rsmd.getColumnType(i)==java.sql.Types.SMALLINT){
         obj.put(column_name, rs.getInt(column_name));
        }
        else if(rsmd.getColumnType(i)==java.sql.Types.DATE){
         obj.put(column_name, rs.getDate(column_name));
        }
        else if(rsmd.getColumnType(i)==java.sql.Types.TIMESTAMP){
        obj.put(column_name, rs.getTimestamp(column_name));   
        }
        else{
         obj.put(column_name, rs.getObject(column_name));
        }
      }

      json.put(obj);
    }

    return json;
  }
}
    
answered by 07.01.2017 в 08:25