Optimmus
Optimmus

Reputation: 11

Resultset error

Im working with Java EE and derby, i try to get data from my resultset and put them in int and string but don't work it gives me this error :

java.sql.SQLException: Invalid operation for the current cursor location.

i tryed result.next() but nothing, here is my code :

    Connection conn = null;
    Statement stmt = null;
    ResultSet result = null;  

    Hotel hot = new Hotel();
    try {
        synchronized (dataSource) {
            conn = dataSource.getConnection();
        }



        stmt = conn.createStatement();
        String req = "SELECT * FROM hotel WHERE num = " + num;
        result = stmt.executeQuery(req);                                                              

        }

        //result.next();           

        int xxnum = result.getInt(1);
        String nom = result.getString("nom");
        String villeV = result.getString("ville");
        int etoilesV = result.getInt("etoiles");
        String directeur = result.getString("directeur");

        Hotel hol = new Hotel(num, nom, villeV, etoilesV, directeur);                

        result.close();
        stmt.close();
        return hol;
    } catch (SQLException ex) {
        throw new DAOException("probl�me r�cup�ration de la liste des hotels !!", ex);
    } finally {
        closeConnection(conn);
    }

Upvotes: 1

Views: 4447

Answers (2)

Reimeus
Reimeus

Reputation: 159754

The error

java.sql.SQLException: Invalid operation for the current cursor location.

will be caused by not setting the cursor to the next position using

result.next();

Place the call in an if statement

if (result.next()) {
   // build Hotel object
   ...
}

If you still don't see any results, run your SQL directly against your database and see if any records are returned. If not, adjust your query or data accordingly.


Side Notes:

  • Use PreparedStatement to protect against SQL Injection attacks.
  • Place result.close(); and stmt.close(); calls in a finally block.

Upvotes: 5

Srinivas
Srinivas

Reputation: 1790

You need to use next() method of ResultSet.

Check the Javadocs here and I have snipped the relevant part below.

Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

So you need to do this in your code:

if(result.next())
{
    int xxnum = result.getInt(1);
    String nom = result.getString("nom");
    String villeV = result.getString("ville");
    int etoilesV = result.getInt("etoiles");
    String directeur = result.getString("directeur");
}

Upvotes: 2

Related Questions