Sumeet Gavhale
Sumeet Gavhale

Reputation: 800

how to set values from database into the textfield

 private void btgetinvActionPerformed(java.awt.event.ActionEvent evt) {
        //JOptionPane.showMessageDialog(null, "REMITTANCE ID IS VALID!");
        try {
            DBUtil util = new DBUtil();
            Connection con = util.getConnection();
            PreparedStatement stmt = con.prepareStatement("select bk_det.rm_id from bk_det WHERE dbo.bk_det.rm_id = ?");
            ResultSet rs;
            String rm = tf_rmid.getText().trim();
            stmt.setInt(1, Integer.parseInt(rm));
            rs = stmt.executeQuery();
            while (rs.next()) {
                int i = Integer.parseInt(rs.getString("box_no"));
                tfbrname.setText(rs.getString(i));
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());

        }
    }

I am actually trying to search value from my database table called dbo.bk_det. I am taking the value of WHERE from my textfield tf_rmid. Everything goes on well without error but once i insert the rm_id and click on button btgetinv it says 123 which is my rm_id is out of range cant understand where the error is and what is the problem.

Upvotes: 1

Views: 7946

Answers (2)

schtever
schtever

Reputation: 3250

The problem is with the following statements:

int i = Integer.parseInt(rs.getString("box_no"));
tfbrname.setText(rs.getString(i));

The first statement won't work the way you want because there's no column named "box_no" in the select clause. It will throw an exception. Let's assume you change the code to have box_no in the select clause. Then, the second statement will try to retrieve the nth column where the column is the value of box_no. I think you just want:

tfbrname.setText(rs.getString("box_no"));

Again, the above only will work if your SELECT statement includes box_no in the field list.

Upvotes: 1

t_motooka
t_motooka

Reputation: 565

rs.next() returns false if it does not contain any more records. So if you want to behave something when no records found, you have to check record count.

for example,

int recordCount = 0;
while (rs.next()) {
    recordCount++;
    int i = Integer.parseInt(rs.getString("box_no"));
    tfbrname.setText(rs.getString(i));
}
if(recordCount == 0) {
    // do something : report an error or log
}

for further information, see http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#next()

Upvotes: 1

Related Questions