Louw
Louw

Reputation: 63

Can't print information from SQL in Java

The user must choose a Resort ID from the table that is displayed and the make a booking. I can't seem to find my problem, I want to print the name of the Resort that they are making a booking at.

String x = jTextFieldID.getText();
    Integer Resort = Integer.valueOf(x);
    int resort = Integer.parseInt(x);
    String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = "+Resort;  
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, resort);
                try (ResultSet rs = pstmt.executeQuery()) {
                    if (rs.next()) {
                    String resortName = rs.getString("RESORT_NAME");
                    JOptionPane.showMessageDialog(null,
                    "You want to book at " + resortName);
    }

Upvotes: 1

Views: 297

Answers (3)

Joop Eggen
Joop Eggen

Reputation: 109547

The error is that sql is passed to Statement.executeQuery(String) too, instead of the PreparedStatement.executeQuery().

int resort = Integer.parseInt(x);
//String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = ?";  
String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = " + resort;  
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
    //pstmt.setInt(1, resort);
    try (ResultSet rs = pstmt.executeQuery()) {
        if (rs.next()) {
            String resortName = rs.getString("RESORT_NAME");
            JOptionPane.showMessageDialog(null,
                "You want to book at " + resortName);
        }
    }
} catch (SQLException ex) {
    Logger.getLogger(Booking.class.getName()).log(Level.SEVERE, null, ex);
}

Commented is the alternative usage of a prepared statement (as normally used).

Also you should close statement and result set, which can be done automatically with try-with-resources as above.

Oh, oversaw almost, that rs.next() must be called. (The others already mentioned.)

Upvotes: 1

cнŝdk
cнŝdk

Reputation: 32145

You need to test over the ResultSet result before trying to read from it:

if(rs.next()) {
    String ResortName = rs.getString(1);
    JOptionPane.showMessageDialog(null, "You want to book at "+ResortName);
}

And you can use getString(1) to get the RESORT_NAME, check ResultSet .getString(int index) method for further details.

Upvotes: 2

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59978

You have to use rs.next() :

ResultSet rs = pstmt.executeQuery(sql);
String resortName = "";
if(rs.next()){//<<-----------------------------
  resortName = rs.getString("RESORT_NAME");
}

JOptionPane.showMessageDialog(null, "You want to book at "+resortName);

If you want to get many results you can use while(rs.next){...} instead.


Note? for a good practice, don't use upper letter in beginning for the name of your variables ResortName use this instead resortName

Upvotes: 3

Related Questions