[英]I can't use JNDI in tomcat to connect MySQL
我做了這一切: 如何連接 tomcat 7 和 mysql
但它仍然不起作用......為什么? 我錯過了什么?
操作系統:Win7
Eclipse : J2EE 火星
Tomcat : tomcat 8.0
爪哇:1.8.0_73
數據庫名稱:測試
用戶名:root
密碼:123
writeDB testDB = new writeDB(tablename);
....
Class.forName("com.mysql.jdbc.Driver");
try{
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
//-------error-------
dataSource = (DataSource) envContext.lookup("jdbc/test");
//-------error-------
}catch(NamingException ex)
{
throw new RuntimeException(ex);
}
<!-- MySQL JNDI -->
<resource-ref>
<description>MySQL DB</description>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
(在 TOMCAT_HOME/conf 中)
(也在 localhost-config 的 workspace\\Servers\\Tomcat v8.0 Server 中)
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/eatST">
<Resource
name="jdbc/test"
auth="Container"
type="javax.sql.DataSource"
maxActice="100"
maxIdle="30"
maxWait="10000"
username="root"
password="123"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test?
useUnicode=true&characterEncoding=UTF8"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
/>
</Context>
Servlet.service() for servlet [commentCtr] in context
with path [/eatST] threw exception
java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp2.BasicDataSource
cannot be cast to javax.activation.DataSource
at com.joe.db.writeDB.<init>(writeDB.java:58)
at com.joe.servlet.CommentCtr.doPost(CommentCtr.java:38)
at ............
您已導入(並且可能已編程)不正確的DataSource
。 您的異常( java.lang.ClassCastException ... cannot be cast to javax.activation.DataSource
)告訴您您已使用javax.activation.DataSource
,但您想要javax.sql.DataSource
。 修改com.joe.db.writeDB
並更改
import javax.activation.DataSource;
到
import javax.sql.DataSource;
此外,您不需要Class.forName("com.mysql.jdbc.Driver");
(它沒有任何傷害,但 JDBC 驅動程序現在注冊自己)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.