I am trying to accomplish the following (using Netbeans 11.3):
1.) Get Data (String) From a Column in an SQL Table.
2.) Convert and save the Data as a JSONArray using Filewriter.
3.) Query the newly created JSON file (output.json) so the data can be used to populate text boxes.
I have accomplished (I think) 1 and 2; but am stuck on how to save the output.json file so that it can be accessed and queried. As a side note, from my research I think there are much better ways to accomplish these tasks (seeming to me like .php is better suited to these tasks than Java), but as a learning experience I'd like to try to finish this task.
Here is the code:
DatabasetoJSONScript.JS
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class DataBaseToJSon {
public static ResultSet RetrieveData() throws Exception {
String host = "jdbc:derby://localhost:1527/dbname";
String uName = "my Uname";
String uPass = "my Pass";
Connection con = DriverManager.getConnection(host, uName, uPass);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery ("Select * from Table_Name");
return rs;
}
public static void main (String args[])throws Exception {
JSONObject jsonObject = new JSONObject();
JSONArray array = new JSONArray();
ResultSet rs = RetrieveData();
while (rs.next()) {
JSONObject record = new JSONObject();
record.put("TEXT", rs.getString("TEXT"));
record.put("ANSWER", rs.getString("ANSWER"));
array.add(record);
}
jsonObject.put("RC1", array);
try {
try (FileWriter file = new FileWriter ("C:\\Users\\Owner\\Documents\\NetBeansProjects
\\HTML5Application\\public_html")) {
file.write (jsonObject.toJSONString());
}
} catch(IOException e){
System.out.println("JSON flie created....");
}
}
The relevant part of controller.js
$(document).ready(function (){
var questionBank=new Array;
var currentQuestionNumber;
var currentAnswer;
var numberOfQuestions;
var gamePosition;
var score;
$.getJSON('output.json', function(output) {
numberOfQuestions=output.RC1.length;
for(i=0;i<output.RC1.length;i++){
typeArray=[];
typeArray[1]=output.RC1[i].TEXT;
typeArray[0]=output.RC1[i].ANSWER;
questionBank[i]=typeArray;
}