我不确定我是否在尝试正确地“打印”我的结果。我想做的是使用 JSP 获取变量,然后将其传递给 servlet,它将查询数据库,然后显示结果。我测试了在不同的 java 文件中查询我的数据库,我没有遇到任何问题。任何建议将不胜感激!
JSP 文件:
<form method="post" action="HelloServlet"/>
Enter your name:<input name = "exName"/><br>
<input type = "submit" />
</form>
JAVA 文件(servlet):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
//response.setContentType("text/html; charset=ISO-8859-1");
PrintWriter out = response.getWriter();
java.sql.Connection con = null;
java.sql.PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/masters";
String user = "christine";
String password = "password";
try{
String exName = request.getParameter("exName");
con = DriverManager.getConnection(url, user, password);
pst = con.prepareStatement("SELECT * FROM exercise WHERE exercise_name ='"+exName+"';");
rs = pst.executeQuery();
while (rs.next()){
String name = rs.getString("description_txt");
out.print(exName);
out.print(name);
}
}catch(SQLException ex){
}finally {
try {
if (rs != null){
rs.close();
}
if (pst != null){
pst.close();
}
if (con != null){
con.close();
}
}catch(SQLException ex){
}
}
}
最佳答案
您的代码中几乎没有什么需要更改的。
正如@BalusC 提到的,不要抑制异常。使用 out.println(ex);
或 throw new ServletException(ex)
向浏览器写入异常。这将帮助您找到问题的原因。
在 DriverManager.getConnection()
之前添加 Class.forName("com.mysql.jdbc.Driver");
。
因为您已经在使用 PreparedStatement
使用
pst = con.prepareStatement("SELECT * FROM exercise WHERE exercise_name =?");
pst.setString(1, exName);
rs = pst.executeQuery();
关于mysql - 使用 JSP 和 Servlet POST 方法查询 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15891702/