sianek sianek - 7 months ago 22
Java Question

java.lang.ClassCastException: org.apache.derby.client.am.ClientPreparedStatement42 cannot be cast to org.apache.derby.iapi.sql.PreparedStatement

I want to create my first project connected with the apache-derby.

public Circle getCircle(int circleId){

Connection conn = null;

try {

conn = dataSource.getConnection();

**PreparedStatement ps = (PreparedStatement) conn.prepareStatement("SELECT * FROM circle where id = ?");
((java.sql.PreparedStatement) ps).setInt(1,circleId);
Circle circle = null;
ResultSet rs = ((java.sql.PreparedStatement) ps).executeQuery();
if(rs.next()){
circle = new Circle(circleId,rs.getString("name"));
}**
rs.close();
((Connection) ps).close();
return circle;
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally{
try{
conn.close();
}catch (SQLException e){}
}
}


public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}


}

dataSource is defined as bean in my .xml file. Using Spring or not i have an error connected with the prepared statement :

Exception in thread "main" java.lang.RuntimeException: java.lang.ClassCastException: org.apache.derby.client.am.ClientPreparedStatement42 cannot be cast to org.apache.derby.iapi.sql.PreparedStatement
at JdbcDemo.dao.JdbcDaoImpl.getCircle(JdbcDaoImpl.java:42)
at JdbcDemo.JdbcDemo.main(JdbcDemo.java:17)
Caused by: java.lang.ClassCastException: org.apache.derby.client.am.ClientPreparedStatement42 cannot be cast to org.apache.derby.iapi.sql.PreparedStatement
at JdbcDemo.dao.JdbcDaoImpl.getCircle(JdbcDaoImpl.java:30)
... 1 more


Could someone can help me ? I can add other class but i think probem is located in this class. I am using apache 10.12.1.1. Thank you for your help :)

Answer

It looks like you are using the wrong import for PreparedStatement. Your import should be:

import java.sql.PreparedStatement;

There should not be any import for org.apache.derby.iapi.sql.PreparedStatement, this is not something you should be using here.

You do not need any casts in your code:

PreparedStatement ps = conn.prepareStatement("SELECT * FROM circle where id = ?"); 
ps.setInt(1, circleId);
Circle circle = null;
ResultSet rs = ps.executeQuery();