Write to oracle 11.2 database from java 8 via Tomcat 8.5.9 using OraclePreparedStatement?

Viewed 2033

I'm having trouble writing to an Oracle 11.2 database using Java 8 with Tomcat 8.5.9. Actually, the following code works fine for writing to a stored procedure, but I get an error when writing to the database directly.

Context initCtx = new InitialContext(); 
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/myPool");
conn = ds.getConnection(); 

// The following works fine:   
cs = conn.prepareCall( "{call my_proc (?,?)}" );
cs.setString(1, var1);
cs.registerOutParameter(2, Types.VARCHAR); 
cs.execute();
out_var2 = cs.getString(2);

// The following results in a ClassCastException error:
sql ="INSERT INTO MY_TABLE1 (my_value1, my_value2) VALUES (?,?)";
ps = (OraclePreparedStatement) conn.prepareStatement(sql);

// The following results in the same error, but is an example of using Oracle extensions for setXXX():
sql="INSERT INTO MY_TABLE2 (my_value3, my_value4) VALUES (?,?)";
ps = (OraclePreparedStatement) conn.prepareStatement(sql);       
for (ii=0; ii<var100.length; ii++) {
     ps.setBinaryFloat(3,  my_value3[ii]);
     ps.setBinaryDouble(4, my_value4[ii]);
     ps.addBatch();
}
ps.executeBatch();

The error is: java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement cannot be cast to oracle.jdbc.OraclePreparedStatement.

I recently switched from GlassFish to Tomcat. The previous code that was working for Glassfish was:

OracleDataSource ods = ds.unwrap(OracleDataSource.class);
OracleConnection conn = (OracleConnection) ods.getConnection();
conn = ds.getConnection();
sql_a ="INSERT INTO MY_TABLE (my_value1, my_value2) VALUES (?,?)";
ps_a = (OraclePreparedStatement) conn.prepareStatement(sql_a);

but it gives the error, java.lang.NullPointerException with Tomcat.

I've configured my tomcat files using the following link as a guide:

https://tomcat.apache.org/tomcat-8.5-doc/jndi-datasource-examples-howto.html

specifically the section on Oracle 8i, 9i, & 10g (context configuration and web.xml).

Any idea how I can get eliminate the Tomcat error when I write to the database directly, while also allowing the above code to continue working when writing to a stored procedure?

2 Answers
Related