我不确定我是否正在尝试正确“打印”我的结果。我想要做的是使用 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){
}
}
}