0

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
s5s
  • 11,159
  • 21
  • 74
  • 121
  • You can't cast because this is a logical statement from your connection pool that wraps the physical statement of the driver. Have you tried using `Statement.unwrap(..)` instead of trying to cast? You also may need to set certain connection pool properties to allow it to unwrap. – Mark Rotteveel Aug 13 '19 at 18:59
  • Bug in c3p0: https://stackoverflow.com/questions/38270883/c3p0-0-9-5-2-statement-unwrap-cause-abstractmethoderror – s5s Aug 14 '19 at 11:14
  • According to the 3 year old answer there, it was already fixed. If you can't use `unwrap`, then you are using an older version of c3p0. – Mark Rotteveel Aug 14 '19 at 11:17
  • @MarkRotteveel Yes, I'm just adding it for future readers. It seems to have been fixed and if one updates their c3p0 version `unwrap` should work. – s5s Aug 14 '19 at 11:35

1 Answers1

0

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)

s5s
  • 11,159
  • 21
  • 74
  • 121