也许有人可以举例说明在数据库中存储和检索数据的servlet?谢谢。
答案 0 :(得分: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());
}
}
}
}
前进并加强它。希望有所帮助。