我正在servlet中创建一个名为讨论论坛的项目...... 但我坚持在查询中从给定主题的数据库中获取结果... 我创建了一个名为index的servlet,其中有一个主题,当我点击主题时我遇到了一些错误,例如MessageDisplayed servlet中的'strong>未知列'pepsi'在'where子句' ...我认为查询中存在问题... 索引servlet的编码是:
@WebServlet("/Index")
public class Index extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String url = "jdbc:mysql://localhost:3306/df";
String driver = "com.mysql.jdbc.Driver";
String USER = "root";
String PASS = "root";
try {
Class.forName(driver);
Connection conn = (Connection) DriverManager.getConnection(url, USER, PASS);
out.print("<html><body>");
out.print("<a href='PostTopic'><input type='submit' value='Post New Topic'></a><br><br>");
String sql = "select topic_name from topic";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
String topic_name = rs.getString("topic_name");
HttpSession session = request.getSession();
session.setAttribute("topic_name", topic_name);
out.print("<a href='MessageDisplayed'>");
out.print(topic_name);out.print("</a>");
out.print("<br>");
}
out.print("</body></html>");
} catch (Exception e) {
out.print(e.getMessage());
}
out.close();
}
}
并且MessageDisplayed servlet的编码是:
public class MessageDisplayed extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String url = "jdbc:mysql://localhost:3306/df";
String driver = "com.mysql.jdbc.Driver";
String USER = "root";
String PASS = "root";
try{
Class.forName(driver);
Connection conn = (Connection) DriverManager.getConnection(url, USER, PASS);
HttpSession session = request.getSession();
String topic = (String) session.getAttribute("topic_name");
String sql = "select user_name,comment from comments where topic_name="+topic;
PreparedStatement ps = conn.prepareStatement(sql);
// ps.setString(1, topic);
ResultSet rs = ps.executeQuery();
while(rs.next()){
String name = rs.getString("user_name");
String comment = rs.getString("comment");
out.print("<html><body>");
out.print("Name : "+name);out.print("<br>");out.print("Message : "+comment);out.print("<br>");
out.print("</body></html>");
}
}
catch(Exception e){
out.print(e.getMessage());
}
out.close();
}
}
数据库有2个表主题表(topic_id,topic_name)和一个注释表(comment_id,comment,user_name,topic_id)插入工作正常... 但我无法取得结果 请尽快帮帮我....
答案 0 :(得分:1)
我认为错误就在这一行
String sql = "select user_name,comment from comments where topic_name="+topic;
此外,您使用的方式不是使用PreparedStatement的正确方法。
使用这种方式
PreparedStatement ps = conn.prepareStatement("select user_name,comment from comments where topic_name=?");
ps.setString(1,topic);