--->大家好,我试图连接servlet与mysql,但我不知道为什么我得到ClassNotFoundException?它出现在class.forName行中。数据库名称为trial1,表名为data2,其中包含列ID,名称,工资。请帮助。
*import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;
/**
* Servlet implementation class dbHandling
*/
@WebServlet("/dbHandling")
public class dbHandling extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public dbHandling() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final String JDBC_DRIVER="com.mysql.jdbc.Driver";
final String DB_URL="jdbc:mysql://localhost/trial1";
// Database credentials
final String USER = "root";
final String PASS = "root";
Connection conn = null ;
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"red\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n");
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();/*This is where exception is occuring*/
conn = (Connection) DriverManager.getConnection(DB_URL,USER,PASS);
stmt = (Statement) conn.createStatement();
String sql;
sql = "SELECT * from data2";
System.out.println(sql);
ResultSet rs = (ResultSet) stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
int age = rs.getInt("age");
String salary = rs.getString("salary");
out.println("ID: " + id + "<br>");
out.println(", Age: " + age + "<br>");
out.println(", First: " + salary + "<br>");
}
out.println("</body></html>");
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
答案 0 :(得分:0)
错误意味着应用程序正在查找无法找到的类,并且正确地将其置于错误上
Class.forName("com.mysql.jdbc.Driver").newInstance();
这是因为系统正在尝试加载未放入类路径的mysql连接器类。请下载最新的Jar文件并将其放在类路径中。有关如何将jar添加到类路径的更多信息,请参阅this