0

也许有人可以举一个 servlet 在数据库中存储和检索数据的例子?谢谢你。

4

1 回答 1

1

不是最好的代码,但它会让你开始:

    public class MyServletGetsDataFromDb extends HttpServlet {
      public static final JDBC_URL = "whtever:my://database/is?connection=parameters";
      public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Connection conn = null;
        try {
          conn = DriverManager.getConnection(JDBC_URL);
          ResultSet results = conn.createStatement("SELECT id from table").executeQuery();
          response.setContentType("text/plain");
          while (results.next()) {
              response.getWriter().write(results.getString(1)+"\n");
          }
        } catch (SQLException e) {
          response.setStatusCode(500);
          throw new ServletException(e.getMessage());
        } finally {
          try {
            if (conn != null) conn.close();
          } catch (SQLException e) {
          response.setStatusCode(500);
          throw new ServletException(e.getMessage());
          }
        }
      } 
   }

前进并增强它。希望有帮助。

于 2013-01-14T16:19:14.763 回答