【发布时间】:2019-07-30 09:57:59
【问题描述】:
我想通过 try-catch 方法连接到 MySQL 数据库。但是我的 Eclipse 控制台继续显示我的 catch 块中的“GOT AN ERROR”。请帮助我解决这个问题,因为我是 Java 和异常处理的新手。以下是我的代码。
public class MyServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String task;
String tm;
task = request.getParameter("task");
tm= request.getParameter("reminder_time");
// System.out.println("task = "+task+"time ="+tm);
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date parsedDate = dateFormat.parse(tm);
java.sql.Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
//System.out.println("Time=");
Connection con =DriverManager.getConnection(
"jdbc:mysql://localhost:3306/reminder","xyz","xyz123");
String INSERT_RECORD = "insert into ToDo values(?, ?)";
PreparedStatement pstmt = null;
pstmt.close();
pstmt = con.prepareStatement(INSERT_RECORD);
pstmt.close();
pstmt.setString(1, task);
pstmt.close();
//pstmt.setDate(2, timestamp);
pstmt.close();
int rs= pstmt.executeUpdate();
if(rs!=0){
// response.sendRedirect("success.html");
// return;
PrintWriter out= response.getWriter();
out.println("Successfull");
pstmt.close();
con.close();
}
else{
// response.sendRedirect("error.html");
PrintWriter out= response.getWriter();
out.println("Failed");
}
}
catch (Exception e) {
System.out.println("Got an ERROR");
}
}
}
提前致谢。
【问题讨论】:
-
致电
e.printStackTrace()以获取有关异常的更多详细信息(或至少打印e.getMessage())。此外,不确定在执行查询之前关闭语句是否是个好主意。 -
将此
System.out.println("Got an ERROR: "+ e.getMessage);和下一行e.printStackTrace()添加到您的catch块中。这将为您提供错误原因和堆栈跟踪。然后你会看到出了什么问题。 -
所有那些 PreparedStatement 关闭都会导致问题。尝试关闭 PreparedStatement 很好,但最好将关闭调用移动到 finally 块中,或者最好仍然使用 try-with-resources 语句
标签: java mysql exception try-catch