Rainzo78
Rainzo78

Reputation: 51

Set text of Text Field from content of ResultSet

i have been trying a lot of syntax but i can't figured it out. I want to display "Invoice number" from my databases to the text field (The field "invoice" from table "transaksi" is already filled with number) But it won't show anything. Here's my code :

private void InvoiceActionPerformed(java.awt.event.ActionEvent evt) {                                        
   ResultSet aa = null;
    try {   
    koneksi objKoneksi = new koneksi();
        Connection kon = objKoneksi.bukaKoneksi();
        Statement stat = kon.createStatement();
    String query ="select invoice from transaksii";
    String res = aa.getString(query);
    Invoice.setText(res);
   }
   catch (SQLException e) {}
}    

Note : - Invoice is Former JTextField1. - transaksii = name of my table. - invoice = name of the field.

Thank you. English is not my native language.

Upvotes: 0

Views: 2924

Answers (2)

Blip
Blip

Reputation: 3171

There is only 1 problem in your original code. The result set that has returned in the line aa = stat.executeQuery(query); is presently at the a position before the 1st result returned. So When you call aa.getString it is not going to return any thing as it is before the 1st result. Also the ResultSet.getString takes a parameter of int or a parameter of String representing the column name. But in your case you have passed the query as the parameter.

So the corrected code should be if you only want to return the 1st item of the ResultSet would be :

private void InvoiceActionPerformed(java.awt.event.ActionEvent evt) {                                        
   ResultSet aa = null;
    try {   
    koneksi objKoneksi = new koneksi();
        Connection kon = objKoneksi.bukaKoneksi();
        Statement stat = kon.createStatement();
        String query ="select invoice from transaksii";
        aa = stat.executeQuery(query);
        String res = "";
        if(aa.next()){ // checks and moves it to 1st position
           res = aa.getString("invoice"); //column name of the column
        }
        Invoice.setText(res);
   }catch(SQLException e){
        e.printStackTrace();
   }finally{
        //The closing of connection, statement and resultset.
   }
}

Upvotes: 1

singhakash
singhakash

Reputation: 7919

You did not execute the query. The value of aa is null and you might be getting a NullPointerException.

String query ="select invoice from transaksii";
aa=stat.executeQuery(query);
if(aa.next())
String res = aa.getString("invoice");

Note: Its not a good practice to have an empty catch because you would then end up without knowing about the exception like now. You should do e.printStackTrace(); in catch block.

Upvotes: 1

Related Questions