Class.forName 连接 mysql驱动一直抛出 ClassNotFoundException 异常,解决方法如下:
一、将 mysql-connector-java-5.1.47.jar 复制到 WebContent\WEB-INF\lib 目录中。如下:
C:\Software\java\workspaces\web1\myweb1\WebContent\WEB-INF\lib\mysql-connector-java-5.1.47.jar
二、右键项目 - Properties - Java Build Path - Libraries - Add JARs - JAR Selection -
找到 mysql-connector-java-5.1.47.jar - OK - Apply - OK
三、连接 MySQL 正常,全部下面代码。
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<table border="1">
<%
String url = "jdbc:mysql://127.0.0.1:3306/mysqldbname?useUnicode=true&characterEncoding=utf8";
String user = "root";
String password = "root";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,user,password);
if ( con.isClosed() ) {
out.println( "failed to connect the database");
return;
}
Statement statement = con.createStatement();
String sql = "SELECT * FROM `users`";
ResultSet rs = statement.executeQuery(sql);
String category = null;
String id = null;
String name = null;
String value = null;
while( rs.next() ){
category = rs.getString("category");
id = rs.getString("id");
name = rs.getString("name");
value = rs.getString("value");
out.println("<tr>");
out.println("<td>" + id + "</td>");
out.println("<td>" + name + "</td>");
out.println("<td>" + value + "</td>");
out.println("<td>" + category + "</td>");
out.println("</tr>");
}
rs.close();
con.close();
out.println( "succeeded connecting to the database");
}catch(SQLException e){
e.printStackTrace();
}
%>
</table>
</body>
</html>