码迷,mamicode.com
首页 > 数据库 > 详细

如何使用servlet访问mysql数据库

时间:2015-08-05 16:15:46      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

1. 连接mysql数据库,选取的是name字段,把class文件放到Tomcat安装文件目录/webapps/test/WEB-INF/classes

 1 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数据库

标签:

原文地址:http://www.cnblogs.com/crows/p/4704972.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!