JavaWeb程序對SQLserver數據庫的增刪改查操作


聲明:學了幾天終於將增刪改查的操作掌握了,也發現了一些問題,所以總結一下.

重點:操作數據庫主要用的是SQL語句跟其他無關.

 

一:前提知識:PreparedStatement

PreperedStatement是Statement的子類,它的實例對象可以通過調用Connection.preparedStatement()方法獲得,相對於Statement對象而言:PreperedStatement可以避免SQL注入的問題。
  Statement會使數據庫頻繁編譯SQL,可能造成數據庫緩沖區溢出。PreparedStatement可對SQL進行預編譯,從而提高數據庫的執行效率。並且PreperedStatement對於sql中的參數,允許使用占位符的形式進行替換,簡化sql語句的編寫。

舉例:

1 PreperedStatement mi = Connection.preparedStatement();
2 try{
3 i = mi.executeUpdate();
4  }catch(Exception e){
5  if(i != 1)
6 {
7  System.out.println("修改不成功");
8  }
9  }

二:實際例子:

1: 編寫index.jsp文件通過JSTL中的<c:redirect>標簽指向servlet

  1 package com.ll;
  2 
  3 import java.io.IOException;
  4 import java.sql.*;
  5 import java.util.ArrayList;
  6 import java.util.List;
  7 
  8 import javax.servlet.ServletException;
  9 import javax.servlet.annotation.WebServlet;
 10 import javax.servlet.http.HttpServlet;
 11 import javax.servlet.http.HttpServletRequest;
 12 import javax.servlet.http.HttpServletResponse;
 13 
 14 import dao.Studentdao2;
 15 
 16 /**
 17  * Servlet implementation class GoodsServlet
 18  */
 19 @WebServlet("/GoodsServlet")
 20 public class GoodsServlet extends HttpServlet {
 21     private static final long serialVersionUID = 1L;
 22        
 23     /**
 24      * @see HttpServlet#HttpServlet()
 25      */
 26     public GoodsServlet() {
 27         super();
 28         // TODO Auto-generated constructor stub
 29     }
 30 
 31     /**
 32      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 33      */
 34     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 35         // TODO Auto-generated method stub
 36         String action = request.getParameter("action");
 37         if(action.equals("zongjin")){
 38             
 39             try {
 40                 query(request,response);
 41             } catch (Exception e) {
 42                 // TODO Auto-generated catch block
 43                 e.printStackTrace();
 44             }
 45         }
 46         
 47         
 48         
 49     }
 50 
 51     /**
 52      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 53      */
 54     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 55         // TODO Auto-generated method stub
 56     }
 57     
 58     
 59     public void query(HttpServletRequest request, HttpServletResponse response) throws Exception{
 60         Studentdao2 conn = new Studentdao2();
 61         String sql = "Select *from Student";
 62     
 63          /*
 64         //調用函數去向數據庫中添加數據
 65           String addsql = "於海-19-軟件1501-男";
 66           conn.addsql(addsql);
 67          */ 
 68         
 69         
 70         /*
 71          //刪除數據庫中的數據
 72         String strdelete = "Delete from Student Where 姓名 = '於海'";
 73         conn.deletesql(strdelete);
 74         */
 75         
 76         /*
 77          //修改數據庫中的數據
 78         String update = "Update Student set 姓名='宗進' Where 姓名 = '小明' ";
 79         conn.updateSql(update);
 80         */
 81         
 82         
 83         ResultSet rs =conn.executeQuery1(sql);//調用自制函數來接受查詢的結果
 84         List list = new ArrayList();
 85         while(rs.next())
 86         {
 87             Student f = new Student();
 88             //equals比較的結果為false是因為從數據庫中返回的字符串為"宗進          "    
 89             f.setBanji(rs.getString("班級"));
 90             f.setName(rs.getString("姓名"));
 91             f.setSex(rs.getString("性別"));
 92             f.setTime(rs.getString("年齡"));        
 93             
 94             list.add(f);
 95             
 96         }
 97         
 98         request.setAttribute("list", list);
 99         request.getRequestDispatcher("sql2.jsp").forward(request, response);
100         
101         
102         
103         
104     }
105     public String cat(String str){
106         String[] arr = str.split(" ");
107         String s = arr[0];
108         return s;
109         
110     }
111 
112 }

3.Servlet的web.xml文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 3   <display-name>JSTL</display-name>
 4   <welcome-file-list>
 5     <welcome-file>index.html</welcome-file>
 6     <welcome-file>index.htm</welcome-file>
 7     <welcome-file>index.jsp</welcome-file>
 8     <welcome-file>default.html</welcome-file>
 9     <welcome-file>default.htm</welcome-file>
10     <welcome-file>default.jsp</welcome-file>
11   </welcome-file-list>
12   <jsp-config>
13     <taglib>
14       <taglib-uri>http://java.sun.com/jstl/fmt</taglib-uri>
15       <taglib-location>/WEB-INF/tld/fmt.tld</taglib-location>
16     </taglib>
17     <taglib>
18       <taglib-uri>http://java.sun.com/jstl/core</taglib-uri>
19       <taglib-location>/WEB-INF/tld/c.tld</taglib-location>
20     </taglib>
21     <taglib>
22       <taglib-uri>http://java.sun.com/jstl/sql</taglib-uri>
23       <taglib-location>/WEB-INF/tld/sql.tld</taglib-location>
24     </taglib>
25     <taglib>
26       <taglib-uri>http://java.sun.com/jstl/x</taglib-uri>
27       <taglib-location>/WEB-INF/tld/x.tld</taglib-location>
28     </taglib>
29   </jsp-config>
30   
31   <servlet>
32       <servlet-name>GoodsServlet</servlet-name>
33       <servlet-class>com.ll.GoodsServlet</servlet-class>
34   </servlet>
35   
36   <servlet-mapping>
37        <servlet-name>GoodsServlet</servlet-name>
38        <url-pattern>/com.ll.GoodsServlet</url-pattern>
39   </servlet-mapping>
40   
47   
48 </web-app>

4.創建一個用於連接數據庫並且處理的類

 1 package dao;
 2 
 3 import java.io.InputStream;
 4 import java.sql.Connection;
 5 import java.sql.DriverManager;
 6 import java.sql.PreparedStatement;
 7 import java.sql.ResultSet;
 8 import java.sql.SQLException;
 9 import java.sql.Statement;
10 import java.util.Properties;
11 
12 public class Studentdao2 {
13      public Connection conn = null;
14      public String url = null;
15      public Statement stmt = null;
16      public ResultSet rs = null;
17      public static String propFilename = "Studentdao2.properties";
18      private static Properties prop = new Properties();
19      private static String  dbClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
20      private static String dbUrl = "jdbc:sqlserver://localhost:1433;DatabaseName=StudentManagement";
21      private static String  addSql = "insert into Student values(?,?,?,?)";
22      private static String updateSql = "update Student set 姓名=?,年齡=?,班級=?,性別=?";//用於整體修改數據庫中的值
23      public Studentdao2(){
24          try{
25             // InputStream in = getClass().getResourceAsStream(propFilename);
26             // prop.load(in);
27             // dbClassName = prop.getProperty("DB_URL",dbUrl);
28             // dbUrl = prop.getProperty("DB_URL", dbUrl);
29              Class.forName(dbClassName);
30              conn = DriverManager.getConnection(dbUrl, "sa", "zongjin123");
31              if(conn != null)
32              {
33                  System.out.println("連接成功");
34              }
35              else{
36                  System.out.println("連接失敗");
37              }
38              stmt = conn.createStatement();
39              
40          }catch(Exception e){
41              e.printStackTrace();
42          }
43          
44      }
45     public ResultSet executeQuery1(String sql) throws Exception {
46         // TODO Auto-generated method stub
47         this.rs = this.stmt.executeQuery(sql);
48         return this.rs;
49     }
50     public void addsql(String sql) throws Exception{
51         PreparedStatement add = conn.prepareStatement(addSql);
52         String[] shuju = sql.split("-");
53         System.out.println(shuju[0]);
54         add.setString(1, shuju[0]);
55         add.setString(2,shuju[1]);
56         add.setString(3,shuju[2]);
57         add.setString(4, shuju[3]);
58         add.executeUpdate();
59         add.close();    
60     }
61     public void deletesql(String sql) throws Exception{
62         int i = 0;
63         PreparedStatement delete = conn.prepareStatement(sql);
64         try{
65            i = delete.executeUpdate();
66         }catch(Exception e){
67             if(i != 1)
68             {
69                 System.out.println("刪除失敗");
70             }
71         }
72         delete.close();
73     }
74     public void updateSql(String sql)throws Exception
75     {
76         PreparedStatement update = conn.prepareStatement(sql);
77         //用於整體修改數據庫中的值,但是一般直接用sq語句來進行操作數據庫
78         //update.setString(2, str);
79         //String[] shuju = sql.split("-");
80         //System.out.println(shuju[0]);
81         //update.setString(1, shuju[0]);
82         //update.setString(2,shuju[1]);
83         //update.setString(3,shuju[2]);
84         //update.setString(4, shuju[3]);
85         update.executeUpdate();
86         update.close();
87     }
88     
89 }

5.編寫用於存儲數據的student類

 1 package com.ll;
 2 
 3 public class Student {
 4     private String name;
 5     private String time;
 6     private String banji;
 7     private String sex;
 8     public String getBanji() {
 9         return banji;
10     }
11     public void setBanji(String banji) {
12         this.banji = banji;
13     }
14     
15     public String getName() {
16         return name;
17     }
18     public void setName(String name) {
19         this.name = name;
20     }
21     public String getTime() {
22         return time;
23     }
24     public void setTime(String time) {
25         this.time = time;
26     }
27     
28     public String getSex() {
29         return sex;
30     }
31     public void setSex(String sex) {
32         this.sex = sex;
33     }
34     
35 
36 }

6運行index.jsp文件來運行


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM