gpt4 book ai didi

java - 使用 OraclePreparedStatement 通过 Tomcat 8.5.9 从 java 8 写入 oracle 11.2 数据库?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:39:48 24 4
gpt4 key购买 nike

我在使用 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 with Tomcat。

我已经使用以下链接作为指南配置了我的 tomcat 文件:

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

特别是有关 Oracle 8i、9i 和 10g 的部分(上下文配置和 web.xml)。

知道如何在直接写入数据库时​​消除 Tomcat 错误,同时允许上述代码在写入存储过程时继续工作吗?

最佳答案

这就是我在 Tomcat 中的工作方式:

(a) 在context.xml中定义资源,放在webapps//META-INF/context.xml下

<Context>
<Resource name="jdbc/orcldriver_dbcs" auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
username="hr"
password="hr"
url="jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(HOST=myhost)(PORT=1521)(PROTOCOL=tcp))(CONNECT_DATA=(SERVICE_NAME=myorcldbservicename)))"
/>
</Context>

(b) 在 servlet 中,如下所示引用资源。

ctx = new InitialContext();
Context envContext = (Context) ctx.lookup("java:/comp/env");

// Look up a data source
javax.sql.DataSource ds
= (javax.sql.DataSource) envContext.lookup ("jdbc/orcldriver_dbcs");


// With AutoCloseable, the connection is closed automatically.
try (OracleConnection connection = (ds.getConnection()).unwrap(oracle.jdbc.OracleConnection.class))
{

....
doSQLWork();
....
}

关于java - 使用 OraclePreparedStatement 通过 Tomcat 8.5.9 从 java 8 写入 oracle 11.2 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43985601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com