gpt4 book ai didi

java - 数据库try-catch block 代码不执行

转载 作者:行者123 更新时间:2023-11-29 16:13:18 25 4
gpt4 key购买 nike

我想通过try-catch方法连接MySQL数据库。但我的 Eclipse 控制台继续显示“出现错误”,该错误位于我的 catch block 中。请帮助我解决这个问题,因为我是 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");
}
}
}

提前致谢。

最佳答案

要找出调用 catch 子句的数据库访问失败,请尝试这样的代码。

catch (SqlException e) {
System.out.println("database exception");
System.out.println(e);
e.printStackTrace();
}
catch (Exception e)
System.out.println("unexpected exception");
System.out.println(e);
e.printStackTrace();
throw;
}

您需要生成异常的行号,printStackTrace() 会向您显示它。或者,在 Eclipse 的调试器中,在异常处理程序处设置断点并检查异常。

您的代码显示了这一点:

            PreparedStatement pstmt = null;
pstmt.close();

这些行中的第二行生成异常,因为您无法在没有对象的情况下调用方法。

专业提示:在现实世界的许多场景中,无法完成连接与无法完成 INSERT 查询或其他查询有很大不同。连接问题通常意味着数据库服务器已关闭或网络工作不正常。查询问题通常意味着您的程序或数据库逻辑存在某种问题。您可以选择使用两个 try/catch block ,一个用于连接,另一个用于查询。

专业提示:始终缩进代码以正确显示嵌套。 Eclipse(以及大多数 IDE)会为您完成此操作。

关于java - 数据库try-catch block 代码不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55062014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com