Search code examples
javamysqljdbcprepared-statementresultset

The resultset returns empty when connecting with MySQL


I'm trying to execute a query in database in MySQL using PreparedStatement and ResultSet.

The problem is that I am getting an empty result set in MySQL, otherwise I get a correct result on Derby.

Connection con= null;
ResultSet reslt =null;
PreparedStatement ps = null;
try 
{
    //Class.forName("org.apache.derby.jdbc.ClientDriver");
    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/SAIID","SAIID","SAIID"); 
    //con = DriverManager.getConnection("jdbc:derby://localhost:1527/pavillons","saiid","saiid"); 
    String Query =" SELECT * FROM ETUDIANT_PAV WHERE PAVILLONS = ? AND CHAMBRE = ? "

    ps = con.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
    ps.setString(1, "A");
    ps.setString(2, "1");
    reslt = ps.executeQuery();
    //String thequeryresult= reslt.getString("NOM_PRENOM");
    //System.out.println ("this is the query result"+thequeryresult);
    JOptionPane.showMessageDialog(null, "Query Executed");
    //con.close();


}
catch (Exception ex) 
{
    JOptionPane.showMessageDialog(null, ex.getMessage());

}

Solution

  • Seeing this lines :

    reslt = ps.executeQuery();
    //String thequeryresult= reslt.getString("NOM_PRENOM");
    

    If you used that commented line to checked the result, this can't worked. You need to move the cursor of that result set to the first line (start to -1).

    For that, use ResultSet.next() that will return true until there is no more row to read.

    reslt = ps.executeQuery(); 
    while(reslt.next()){ //read all lines
        System.out.println(reslt.getString("NOM_PRENOM"));
    }