我已经遍及整个网络试图找到错误的答案,但是找不到与我的错误匹配的内容,或者我无法理解这种关系。
这是我在Eclipse上运行的错误:
java.lang.NullPointerException
ca.sheridancollege.controllers.CarDealership.doGet(CarDealership.java:63)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
这是我的代码:
package ca.sheridancollege.controllers;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CarDealership
*/
@WebServlet("/CarDealership")
public class CarDealership extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public CarDealership() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String dbURL= "jdbc:mysql://localhost:3306/SheridanUsedCars";
String user = "root";
String password = "1234";
Connection conn = null;
try {
conn = DriverManager.getConnection(dbURL, user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String retrieve = "SELECT manufacturerID, manufacturer, price FROM car INNER JOIN manufacturer GROUP BY manufacturerID";
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(retrieve);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResultSet rs = null;
try {
rs = ps.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.err.println("Error executing "+ps.toString());
try {
while (rs.next()){
int id = rs.getInt("manufacturerID");
String man = rs.getString("manufacturer");
response.getWriter().append("<h1>"+id+" "+man+"</h1>");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
在我看来,它认为rs为null,是否是因为try catch?我似乎无法解决问题。
任何帮助都非常感谢
最佳答案
问题在这里
ResultSet rs = null;
try {
rs = ps.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.err.println("Error executing "+ps.toString());
try {
while (rs.next()){
如果对executeQuery的调用引发异常,则rs将保持为空。由于try-catch块不会停止执行,因此即使rs为null,它也会继续执行,导致您在第63行出现错误