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 }
相關文章
相關標籤/搜索