从HeidiSQL DB读取数据到servlet

时间:2015-06-08 08:00:26

标签: servlets heidisql

我正在创建一个程序,我可以通过servlet将数据添加到数据库中,但我无法将其从数据库恢复到HTML页面。

我正在使用HTML页面,一些JS和两个servlet:一个用于在数据库中输入数据,另一个用于获取数据的servlet。

我从JS函数调用这个servlet,但是我无法告诉debbugger为什么会跳过所有代码。我正在使用eclipse IDE。

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class TodoDisplayServlet
 */
@WebServlet("/TodoDisplayServlet")
public class TodoDisplayServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public TodoDisplayServlet() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
    PreparedStatement stmt = null;
     StringBuffer sb = new StringBuffer();

    Class.forName("com.mysql.jdbc.Driver");

    Connection con1 = null;

        con1 = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/tododb2","targarian","liger");

        String query1 =  "select fname, lname, email, pnum"  + "from tododb2";


            stmt = (PreparedStatement) con1.createStatement();
            ResultSet rs = stmt.executeQuery(query1);

            sb.append("<table>");
            while (rs.next()) {
                sb.append("<tr>");

                sb.append("<td>");
                rs.getString(1);
                sb.append("</td>");

                sb.append("<td>");
                rs.getString(2);
                sb.append("</td>");

                sb.append("<td>");
                rs.getString(3);
                sb.append("</td>");

                sb.append("<td>");
                rs.getString(4);
                sb.append("</td>");

                sb.append("</tr>");

            sb.append("</table>");
            stmt.executeUpdate();
            stmt.close();
            }


         PrintWriter writter = null;
            writter = response.getWriter();
          writter.println(sb.toString());
    }
    catch(Exception e)
    {
        System.out.println("Error :"+e.getMessage());
    }
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
}

}

1 个答案:

答案 0 :(得分:0)

问题出在tododb2上,这是我的数据库名称而不是我的表名。非常感谢先生。驼鹿。