简体   繁体   中英

java.sql.SQLException: Illegal operation on empty result set.Else Statement is not Working out

try {
                    //Class.forName("org.h2.Driver");
                    //Connection conn = DriverManager.getConnection("jdbc:h2:~/test","admin","admin");
                    String m=textField_1.getText();
                    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/logindetails","root","root");
                    //Connection conn1 = DriverManager.getConnection("jdbc:mysql://localhost/logindetails","root","root");


                    String query1="Select * from Details where Username='"+m+"'";
                    PreparedStatement statement1 = conn.prepareStatement(query1);
                    ResultSet res=statement1.executeQuery(query1);
                    res.next();

                    String user;
                    user=res.getString("Username");

                    {

                        if(m.compareTo(user)==0)
                        {

                            JOptionPane.showMessageDialog(null, "CONNECTION SUCCESSFULL & DATA SAVED");

                            DataEntry.this.dispose();
                            login ing= new login();
                            ing.setVisible(true);



                        }

                        else
                        {   

                            String query = "insert into Details values(?,?,?,?,?)";
                            PreparedStatement statement=conn.prepareStatement(query);
                            statement.setString(1, textField.getText());


                            statement.setString(2, textField_2.getText());
                            statement.setString(3, textField_3.getText());
                            statement.setString(4, textField_1.getText());
                            statement.setString(5,String.valueOf(passwordField.getPassword()));
                            statement.execute();

                            }


                    }



                }   

In this else part is not working.it is throwing error "Illegal operation on empty result set".I also interchange the body of both if-else statement but that does not help me out.If statement body is working properly.I think the error is ResultSet statement.Thanks in Advance.

You are not checking if the ResultSet contains a result. Therefore you get an exception when calling res.getString("Username") on an empty ResultSet .

Change:

res.next();

String user;
user=res.getString("Username");

to:

String user = null;
if (res.next())
    user=res.getString("Username");

Then, instead of:

if(m.compareTo(user)==0) {
    ...
}

write:

if (user != null) {
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM