最近在做JSP的數據庫連接操作時,一直出現java.lang.ClassNotFoundException: com.mysql.jdbc.Driver的問題。
1.可能是連接問題。
這是定義的dataBean:
public class dataBean {
private Connection con;
public dataBean(){
String CLASSFROENAME = "com.mysql.jdbc.Driver";
String SERVANDDB = "jdbc:mysql://localhost:3306/jsp";
String USERNAME = "root";
String PASSWORD = "root";
try {
Class.forName(CLASSFROENAME);
con = DriverManager.getConnection(SERVANDDB,USERNAME,PASSWORD);
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException!!!");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("SQLException!!!");
e.printStackTrace();
}
}
public ResultSet getData(){
try {
Statement stm = con.createStatement();
ResultSet result = stm.executeQuery("SELECT * FROM list");
return result;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
}
同樣的配置參數使用PHP連接完全沒有問題,排除參數錯誤。
2.沒有JDBC的驅動包。
缺少驅動包可以在Mysql官網下載最新的驅動包導入。
將下載的jar文件導入到Module/Dependencies:
但是此時還是會出現java.lang.ClassNotFoundException: com.mysql.jdbc.Driver的問題。
最後將這個jar文件導入到工程的web/WEB-INF/lib中,再次重啓服務器,可以正常連接。
3.沒有配置Tomcat連接池
在Tomcat的conf/server.xml中配置
打開tomcat的conf/server.xml文件,找到節點:
<GlobalNamingResources>
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
</GlobalNamingResources>
在該節點中加入相關的池配置信息:
<GlobalNamingResources>
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
<!--配置mysql數據庫的連接池,
需要做的額外步驟是將mysql的Java驅動類放到tomcat的lib目錄下
-->
<Resource name="jdbc/mysqlds"
auth="Container"
type="javax.sql.DataSource"
username="root"
password="root"
maxIdle="30"
maxWait="10000"
maxActive="100"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/jsp" />
</GlobalNamingResources>
在tomcat的conf/context.xml文件中的節點中加入如下內容
<ResourceLink name="jdbc/mysqlds" global="jdbc/mysqlds" type="javax.sql.DataSource"/>
然後在web項目中的WEB-INF目錄下的web.xml中配置
<resource-ref>
<description>mysql數據庫連接池</description>
<res-ref-name>jdbc/mysqlds</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
重啓服務器,解決問題。