结果集 returns 与 MySQL 连接时为空

The resultset returns empty when connecting with MySQL

我正在尝试使用 PreparedStatementResultSet 在 MySQL 中的数据库中执行查询。

问题是我在 MySQL 中得到了一个空结果集,否则我在 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());

}

看到这行:

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

如果您使用该注释行来检查结果,则此方法无效。您需要将该结果集的光标移动到第一行(从-1 开始)。

为此,使用 ResultSet.next() 将 return true 直到没有更多行可读。

reslt = ps.executeQuery(); 
while(reslt.next()){ //read all lines
    System.out.println(reslt.getString("NOM_PRENOM"));
}
String selctedItemPAV = indextostring(jComboBox1.getSelectedIndex()); 
       String selctedItemCH = jList1.getSelectedValue();
       String Query =" SELECT * FROM etudiant_pav WHERE PAVILLONS = ? AND CHAMBRE = ? " ;
       rst = theSelectQuery(Query,selctedItemPAV ,selctedItemCH); //this is the posted function 
         DefaultListModel listModel = new DefaultListModel();
         jList3.setModel(listModel);
         System.out.println (selctedItemCH + "  doppppppppp  " +selctedItemPAV + jComboBox1.getSelectedIndex());

          System.out.println ("doppppppppp222222222");
     if (rst.isBeforeFirst())
     {
          System.out.println ("ttttttttttttttttttttttttttttttttttttttttttttt");    //the excution stops here in application.....
         jList3.setEnabled(true);
         listModel.clear();
         jLabel1.setVisible(false);
        while (rst.next()) 
        {
             String aff="hhh";
             aff= rst.getString("NOM_PRENOM");
             System.out.println ("dooooooooo"+aff);
            listModel.addElement(aff);
         }
        }
     else 
     {
         jLabel1.setVisible(false);
          jList3.setEnabled(false);
        JOptionPane.showMessageDialog(null, "la chambre est vide ");
     }

     rst.close();
  }
  catch (Exception ex){
  }