servlet中如何操作数据库

先下载 mysql-connector-java-5.1.38-bin.jar ,然后把 mysql-connector-java-5.1.38-bin.jar 放到 tomcat 的 lib 目录下,再进行以下操作:
1.  加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
2.  创建数据库url
String url = "jdbc:mysql://localhost:3307/spdb?useSSL=false";
String user = "root";
password = "root";
3.  建立连接
con = DriverManager.getConnection(url,user,password);
4.  创建statement
sta = con.createStatement();
5.  创建查询语句
rs = sta.executeQuery("select passwd from users where username='"+username+"'limit 1");
注意SQL的注入漏洞!

案例代码:
 1 //接收用户名和密码
 2 String username;
 3 String password;
 4 Connection con = null;
 5 Statement sta = null;
 6 ResultSet rs = null;
 7         
 8 try {
 9     username = request.getParameter("username");
10     String passwd = request.getParameter("password");
11         
12     //加载驱动程序
13     Class.forName("com.mysql.jdbc.Driver");
14             
15     //创建数据库url
16     String url = "jdbc:mysql://localhost:3307/spdb?useSSL=false";
17     String user = "root";
18     password = "root";
19             
20     //建立连接
21     con = DriverManager.getConnection(url,user,password);
22             
23     //创建statement
24     sta = con.createStatement();
25             
26     rs = sta.executeQuery("select passwd from users where username='"+username+"'limit 1");
27             
28     if(rs.next()){
29         //说明用户存在
30         String dbPasswd = rs.getString(1);
31         if(dbPasswd.equals(passwd)){
32             //合法
33             //将用户信息存入session
34             HttpSession hs = request.getSession(true);
35             hs.setMaxInactiveInterval(60);
36             hs.setAttribute("name", username);
37                     
38             //跳到下一个页面【servlet提供了两种:sendredirect转向,forward转发】
39             //sendredirect 的 url 应该这样:/web应用名/servlet url
40             response.sendRedirect("/UsersManager/MainFrame?username=" + username + "&password=" + password);
41         }else{
42             //跳回登录页面
43             response.sendRedirect("/UsersManager/LoginServlet");
44         }
45     }else{
46         //跳回登录页面
47         response.sendRedirect("/UsersManager/LoginServlet");
48     }
49             
50 } catch (ClassNotFoundException e) {
51     e.printStackTrace();
52 } catch (SQLException e) {
53     e.printStackTrace();
54 } finally{
55     try {
56         if(null != rs){
57             rs.close();
58         }
59         if(null != sta){
60             sta.close();
61         }
62         if(null != con){
63             con.close();
64         }
65     } catch (SQLException e) {
66         e.printStackTrace();
67             }
68 }

 

posted @ 2016-04-11 14:21  oSHYo  阅读(1115)  评论(0编辑  收藏  举报