Search code examples
javamysqlswingnetbeansresultset

Best way to print data from two columns of mySQL database to jTextfield one after another


I am trying to make a program in which i read an input from the user i.e. in the textfield named gname and store its value to a string called grammar. Now this input is what sorts my output from the database.

Database looks like this enter image description here

So when user enters G1 in the textfield it should display records in such a way

A->ab,A-ab,B->b

But it only shows 1st element when i use if(myRs.next) and last one if i use while(myRs.next().

current output is enter image description here

Here is the code for this:

its all in try catch block

String grammar = gname.getText();

        myCon = DriverManager.getConnection("jdbc:mysql://localhost:3306/grammar", "root", "");
        JOptionPane.showMessageDialog(rootPane, "Connected to database");
        mystmt = myCon.createStatement(
                ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        String query = "SELECT starting_symbol, value from starting_symbol where grammar= '" + grammar + "'";
        String query2 = "SELECT non_terminals, terminals from input_values where grammar= '" + grammar + "'";
        mystmt.addBatch(query);
        mystmt.addBatch(query2);
        myCon.setAutoCommit(false);

        mystmt.addBatch(query);
        mystmt.addBatch(query2);
        myRs = mystmt.executeQuery(query);
        while (myRs.next()) {

            String s = myRs.getString("starting_symbol");
            String val = myRs.getString("value");

            output.setText(s + "-> " + val);

        }
        myRs = mystmt.executeQuery(query2);

        ArrayList<String> list_one = new ArrayList<String>();
        ArrayList<String> list_two = new ArrayList<String>();
        while (myRs.next()) {
            list_one.add(myRs.getString("non_terminals"));
            list_two.add(myRs.getString("terminals"));
            for (int i = 0; i < list_one.size(); i++) {
                output_2.setText(list_one.get(i) + "->" + list_two.get(i));

            }

        }

Please help me in getting the correct outut


Solution

  • Use StringBuilder Luke

    StringBuilder b = new StringBuilder();
    while (myRs.next()) {
    
        String s = myRs.getString("starting_symbol");
        String val = myRs.getString("value");
        if (b.length() > 0) {
            b.append(',');
        }
        b.append(s + "-> " + val);
    
    }
    output.setText(b.toString());
    

    And do the same for output_2 field