Mohammad Goudarzi
Mohammad Goudarzi

Reputation: 13

Can not use executeQuery()

I'm making an application to get data from Database , But I can't use executeQuery in my code. This is exception of my code : java.lang.ClassCastException: org.apache.derby.client.am.ClientStatement cannot be cast to java.beans.Statement at Database.main(Database.java:28) Where is the problem?

Connection MyconObj=null;
Statement MystateObj =null;
ResultSet MyresObj = null;


try {
    MyconObj = DriverManager.getConnection("jdbc:derby://localhost:1527/students", "root", "root");
    MystateObj = (Statement) MyconObj.createStatement();
    String query = "SELECT * FROM ROOT.INFORMATION";
    ResultSet MyresObj = MystateObj.executeQuery(query);


   while(MyresObj.next()){
       int id = MyresObj.getInt("id");
       String name = MyresObj.getString("name");
       String lastname = MyresObj.getString("lastname");
       System.out.println(id + "" + name + "" + lastname);

   }

} catch (Exception e) {
    e.printStackTrace();
}

Upvotes: 1

Views: 530

Answers (1)

Rann Lifshitz
Rann Lifshitz

Reputation: 4090

This is a classic example of how classes with the same name can cause confusion and runtime exceptions:

MystateObj = (Statement) MyconObj.createStatement();

The imports used by the implementation have not been included in the OP code, however, based on the thrown exception:

java.lang.ClassCastException: org.apache.derby.client.am.ClientStatement cannot be cast to java.beans.Statement

The Statement class used in the cast is java.beans.Statement, which has probably been imported. The object which has been returned by MyconObj.createStatement() is of the type org.apache.derby.client.am.ClientStatement and this causes the casting exception during runtime - the returned Object is an extension of java.sql.Statement, as mentioned in the comments above (by Mark Rotteveel).

The import of the Statement is correct but from the wrong library. This can easily occur when using IDEs which allow auto import generation (when more then one class matches the used class name, a drop-down list is displayed for possible imports. Selecting the wrong import is a common event, unfortunately).

Upvotes: 1

Related Questions