1

I'm making a simple java query app. This is just a simple test so I don't care about security or anything

I just want to return data to the ajax post so I can create a HTML table with the data.

It would be something like AJAX REQUEST -> Execute Query -> Return Titles and Data -> Create a table.

How should I return this? I alrady can get the data but how should I send the titles and all rows to create the table??

AJAX

$('#btnSubmit').click(function () {
      var query = $('#query').val();
      console.log(query);
      var environmentName = $('#environmentName').val();
      $.ajax({
          url: '/sql/call',
          type: 'get',
          data: {environmentName: environmentName, query: query},
          success: function (result) {
              console.log(result);
          },
          error: function () {

          }
      })
   });

JAVA

public static String callProfileSQL(String sql, String mtmPort) {
    Connection connection = createConnection(mtmPort);
    String out = "";
    try {
        if(connection != null) {
            PreparedStatement statement = connection.prepareStatement(sql);
            ResultSet rs = statement.executeQuery();
            if (!rs.isBeforeFirst()) {
                out = "No data";
            }
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            while (rs.next()) {
                StringBuilder row = new StringBuilder();
                for(int i = 1; i <= columnCount; i++) {
                    row.append(rs.getString(i)).append("; ");
                    System.out.println(row);
                }
            }
            connection.close();
        }
        else {
            //TODO force error
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return out;
}
  • 1
    Put the logic which creates the table in a function and call that from within the `success` handler. – Rory McCrossan Apr 09 '18 at 08:51
  • **I know how to return...** I just don't know what's the appropriate type for the data I want to pass –  Apr 09 '18 at 08:51
  • An array of the data in JSON format would seem the most obvious. – Rory McCrossan Apr 09 '18 at 08:52
  • Can you explain me how you would do it? I can get the titles like: `rs.getMetaData().getColumnName(i)` and I need to return multiple columns and rows. –  Apr 09 '18 at 08:54
  • 1
    Convert sql results to json -> https://stackoverflow.com/questions/18960446/how-to-convert-a-java-resultset-into-json – Reinstate Monica Cellio Apr 09 '18 at 09:00
  • Sorry, I don't know Java, but I'm, sure if you google how to return JSON you should find lots of results, as it's a common technique. – Rory McCrossan Apr 09 '18 at 09:00

0 Answers0