Search code examples
javaswingjtextfieldresultset

get ResultSet into JTxtField


i want to get my full resultset to display into my JTxtField, but i dotn know how to do it.

This is my code At the moment:

    try{
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        conn3 =     DriverManager.getConnection("jdbc:sqlserver://ARTURO-LAPTOP;user=sa;password=sacompusis;database=PDV");
        st3 = conn3.createStatement();
        rs3= st3.executeQuery("SELECT Nombre_Pdv, SUM(Total) AS Expr1 FROM   VENTA_PLATILLOS GROUP BY Nombre_Pdv");

        while(rs3.next()){
            txt.setText(rs3.getString(1));
        }

    }
    catch(Exception e){
        e.printStackTrace();
    }

However this only gives me the first string of the resultset, how can i get the full result set?


Solution

  • Your while loop may be setting many Strings to the JTextField, but only one will show -- the last one set as the JTextField's text, since it will over-write all text added before.

    If you must show all Strings in the JTextField, then create a StringBuilder object, and within the while loop, append the ResultSet text you get into the StringBuilder, and then after the while loop, use the toString() from the StringBuilder as the text for the JTextField. e.g.,

    StringBuilder sb = new StringBuilder();
    while(rs3.next()){
        sb.append(rs3.getString(1) +"; ");
    }
    txt.setText(sb.toString());
    

    Better: display the text in a JTextArea, appending it in the while loop with "\n".

    StringBuilder sb = new StringBuilder();
    while(rs3.next()){
        sb.append(rs3.getString(1) +"\n");
    }
    myTextArea.setText(sb.toString());
    

    Even better still: display the whole ResultSet data in a JTable by creating a TableModel, either derived from AbstractTableModel for flexibility or DefaultTableModel for ease, and adding rows from the ResultSet into the model using your while loop, and then setting a JTable's TableModel with this created and filled model.