Search code examples
javajdbcconnectionclasscastexception

"java.lang.ClassCastException: org.apache.derby.client.net.NetConnection cannot be cast to smartdatabase.Connection" anyone got any idea why?


I am 100% sure my connection name is correct, "smartdatabase" is the package in which this code exists and "SmartData" is my embedded database within NetBeans IDE 8.2 (I believe it is a Derby database).

package smartdatabase;
import java.sql.*;
import org.apache.derby.jdbc.EmbeddedDriver;

public class Connection {

    private Connection conn = null;
    private Statement stmt = null;

    public Connection() {

    }

    public void getStudents() {
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
            conn = (Connection) 
DriverManager.getConnection("jdbc:derby://localhost:1527/SmartData;create=true;", "root", "The 
password");
        `    `String sql;
            sql = "SELECT Firstname, Surname FROM tblStudents";
            ResultS``et rs = stmt.executeQuery(sql);
            while (rs.next()) {
                String Firstname = rs.getString("FirstName");
                String Surname = rs.getString("Surname");
                System.out.println(Firstname + "    " + Surname);
            }
        } catch (SQLException se) {
            se.printStackTrace();
        } catch (`Exception e) {
            e.printStackTrace();
        }
    }

}

Solution

  • You probably have a class Named Connection in your smartdatabase package. This class is used instead of java.sql.Connection By default the compiler resolves Connection from the same package.

    Try renaming that class or use the fully qualified name (java.sql.Connection) instead of just Connection:

    private java.sql.Connection conn = null;