如何使用servlet访问mysql数据库
时间:2021-07-01 10:21:17
帮助过:2人阅读
import javax.servlet.ServletException;
2 import javax.servlet.http.HttpServlet;
3 import javax.servlet.http.HttpServletRequest;
4 import javax.servlet.http.HttpServletResponse;
5
6 public class ShowRs
extends HttpServlet {
7
8 @Override
9 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
10
11 Connection conn =
null;
12 Statement stmt =
null;
13 ResultSet rs =
null;
14
15 resp.setContentType("text/html"
);
16 resp.setCharacterEncoding("utf8"
);
17 PrintWriter out =
resp.getWriter();
18
19 out.println("<table border=1>"
);
20 out.println("<tr><td>Content:</td></tr>"
);
21
22 try {
23 Class.forName("com.mysql.jdbc.Driver"
);
24 conn = DriverManager.getConnection("jdbc:mysql://localhost/spring?user=root&password=root"
);
25 stmt =
conn.createStatement();
26 rs = stmt.executeQuery("select * from teams"
);
27 while (rs.next()) {
28 out.println("<tr>"
);
29 out.println("<td>" + rs.getString("name") + "</td>"
);
30 out.println("</tr>"
);
31 }
32 out.println("</table>"
);
33
34 }
catch (ClassNotFoundException e) {
35 // TODO Auto-generated catch block
36 e.printStackTrace();
37 }
catch (SQLException e) {
38 // TODO Auto-generated catch block
39 e.printStackTrace();
40 }
41
42 }
43
44 }
2. 配置web.xml文件,路径在/webapps/test/WEB-INF
<servlet>
<servlet-name>ShowRs</servlet-name>
<servlet-class>ShowRs</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowRs</servlet-name>
<url-pattern>/ShowRs</url-pattern>
</servlet-mapping>
3.将mysql-connector-java-xxx.jar加入到/webapps/test/WEB-INF/lib
4.打开网页进行测试,显示成功!
4.1 数据库表teams原始内容
4.2 通过servlet访问的name字段
如何使用servlet访问mysql数据库
标签: