我在使用 Java 8 和 Tomcat 8.5.9 写入 Oracle 11.2 数据库时遇到问题。实际上,以下代码对于写入存储过程来说效果很好,但是在直接写入数据库时出现错误。
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();
错误是:java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement cannot be cast to oracle.jdbc.OraclePreparedStatement
.
我最近从 GlassFish 切换到 Tomcat。之前适用于 Glassfish 的代码是:
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);
但它给出了错误,java.lang.NullPointerException
与雄猫。
我已经使用以下链接作为指导配置了我的 tomcat 文件:
https://tomcat.apache.org/tomcat-8.5-doc/jndi-datasource-examples-howto.html https://tomcat.apache.org/tomcat-8.5-doc/jndi-datasource-examples-howto.html
特别是关于Oracle 8i, 9i, & 10g
(上下文配置和 web.xml)。
知道如何在直接写入数据库时消除 Tomcat 错误,同时又允许上述代码在写入存储过程时继续工作吗?