Search code examples
javajdbcc3p0

NewProxyCallableStatement cannot be cast to SQLServerCallableStatement


I have a generic API which accepts a connection. It would seem that one of the callers passes a connection, the prepareCall of which returns an object of type NewProxyCallableStatement. The following code then fails:

SQLServerCallableStatement stmt = (SQLServerCallableStatement) connection.prepareCall(sprocSQL);

The full exception seen by the caller of the API is:

java.lang.ClassCastException: com.mchange.v2.c3p0.impl.NewProxyCallableStatement cannot be cast to com.microsoft.sqlserver.jdbc.SQLServerCallableStatement

I need to use SQLServerCallableStatement because I am calling a stored procedure with an input argument of type TABLE and SQLServerCallableStatement has a setStructured method which allows constructing table type variables.


Solution

  • The solution is to use the code below:

    SQLServerCallableStatement stmt = connection.prepareCall(sprocSQL).unwrap(com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.class);
    

    If you are using c3p0, you'll need to use a version with the unwrap bug fixed. I tested the above with c3p0-0.9.5.2.

    Reference: unwrap Method (SQLServerCallableStatement)