javaweb連接數據庫並完成增刪改查


一.連接數據庫

1、mysql數據庫的安裝和配置

  在網上找到了篇關於mysql的安裝詳細說明,供讀者自己學習

  https://www.jb51.net/article/23876.htm

2、mysql的基本操作

  找到了篇介紹MySQL的基本操作的文章,簡單易懂,可以很快的學會

  http://www.cnblogs.com/mr-wid/archive/2013/05/09/3068229.html#d22

3、創建數據庫表

  建議大家下載一些MySQL的可視化工具如SQLyog,navicat等相應的教程都可以在網上找到,就不在此和大家一一說明,在此以SQLyog為例。

  打開SQLyog軟件,打開該軟件后,會彈出以下畫面,點擊繼續。

  

  進入鏈接配置界面,點擊上方的New…按鈕,輸入鏈接名稱創建一個鏈接

  

  

  之后在配置界面輸入鏈接密碼。此密碼就是在安裝mysql時設置的密碼。

  

  

  輸入密碼后,點擊連接,如果信息無誤,則進入主界面。如下所示

  

  

  創建數據庫,在左側現實數據庫的區域,點擊右鍵,選擇“創建數據庫”

  

  

  輸入數據庫名稱,字符編碼選擇UTF-8,然后點擊創建,則在左側現實出來了剛剛創建的數據庫。

  

 

4、下載數據庫對應的jar包並導入

  在網上下載JDBC驅動然后導入,使用JDBC需要在工程中導入對應的jar包。數據庫與JDBC包的對應關系可以參考各種數據庫對應的jar包、驅動類名和URL格式。在Eclipse下的導入方法:

  在工程的圖標上右擊,選擇”Properties”,在”Java Bulid Path”中選擇”Add External JARs…”,選擇下載並解壓后獲得的jar包。
  

 

     如果對MySQL進行操作,這時下面的import就不會報錯了:

   

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
以上三句導入語句可用import java.sql.*代替

二.實現增刪改查

 1、准備工作

  1:test01文件夾(里面有所需的頁面資源),我完成的是在里面添加增刪改查操作

     2:myeclipse(版本沒什么要求)  eclipse也行 

     3:數據庫 MySQL

     4:需要了解到的知識點:

                                        servlet

                                        EL與JSTL表達式

                                      項目的基本框架搭建(javaweb經典三層框架)

     5:在myeclipse中建立對應的包結構

      

2、項目的基本框架搭建

 所謂三層框架分別為表述層(WEB層)、業務邏輯層()、數據訪問層()。

    web層(action):包含JSP和Servlet等與web相關的內容,負責與瀏覽器的響應和請求;

    業務層(service):只關心業務邏輯;

    數據層(dao):封裝了對數據庫的訪問細節,數據操作類;
    關系:web層依賴業務層    業務層依賴數據層(這個關系很重要)

ps:除了以上三層框架是我們在寫一個javaweb項目必須的外,還需要一個實體類(entity)。

3、實現數據庫的連接

  需要在MySQL中創建所需數據庫,並將表建好。

  

  

 

  在dao下新建一個DBConn類用來處理對數據進行連接。 這是MySQL的連接方式

   

package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
    //eshop為數據庫名稱,db_user為數據庫用戶名db_password為數據庫密碼
    public static String db_url = "jdbc:mysql://localhost:3306/eshop?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT";
    public static String db_user = "數據庫用戶名";
    public static String db_password = "數據庫密碼";

    public static Connection getConn() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(db_url, db_user, db_password);
            System.out.println("連接成功");
        } catch (Exception e) {
            System.out.println("連接失敗");
            e.printStackTrace();
        }
        return conn;
    }
    
    public static void close(Statement state, Connection conn) {
        if(state!=null) {
            try {
                state.close();
            } catch (SQLException e) {
                e.printStackTrace();    
            }
        }    
        if(conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void close(ResultSet rs, Statement state, Connection conn) {
        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(state!=null) {
            try {
                state.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

4、建立實體類

 在entity包下創建School實體類(實體類中的對象對應數據庫表中的字段數據)

package entity;

public class School{
    private String classname;
    private String classteacher;
    private String classplace;
    
    public String getclassname() {
        return classname;
    }
    public void setclassname(String classname) {
        this.classname=classname;
    }
    
    public String getclassteacher() {
        return classteacher;
    }
    public void setclassteacher(String classteacher) {
        this.classteacher=classteacher;
    }
    
    public String getclassplace() {
        return classplace;
    }
    public void setclassplace(String classplace) {
        this.classplace=classplace;
    }
}

5、實現增刪改查方法

創建方法類,這里有兩種方法

1:在dao包中創建一個SchoolDao接口,里面寫增刪改查的方法,再在dao中創建SchoolDaoImpl類來實現接口,並實現之中的方法。

SchoolDao接口:

package dao;

import java.util.List;

import entity.School;

public interface SchoolDao {
    public boolean add(School school) ;
    public List<School>select();
    public boolean update(String classname,String classteacher,String classplace);
    public boolean delete(String classname);
    public List<School>selectclassname(String classname);

}

SchoolDaoImpl類(包含增刪改查操作):

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import entity.School;

public class SchoolDaoImpl implements SchoolDao{
    Connection conn=(Connection)DBUtil.getConn();
    @Override
public boolean add(School school) {
    
    boolean flag=false;
    
    try {
        String sql="insert into school values('"+school.getclassname()+"','"+school.getclassteacher()+"','"+school.getclassplace()+"')";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        int i = pstmt.executeUpdate();
        pstmt.close();
        conn.close();
        if(i>0) {
            flag = true;
        }

    }catch(SQLException e) {
        e.printStackTrace();
    }
    return flag;    
}
    @Override
public List<School> select(){
    List<School> list = new ArrayList<School>();
    try {
        String sql="select * from school";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        while(rs.next()) {
            School school=new School();
            school.setclassname(rs.getString("classname"));
            school.setclassteacher(rs.getString("classteacher"));
            school.setclassplace(rs.getString("classplace"));
            list.add(school);
        }
        rs.close();
        pstmt.close();
        conn.close();

    }catch(SQLException e) {
        e.printStackTrace();
    }
    
    return list;
}
    @Override
public List<School>selectclassname(String classname){
    List<School> list = new ArrayList<School>();
    try {
        String sql="select * from school where classname=?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1,classname );
        ResultSet rs = pstmt.executeQuery();
        while(rs.next()) {
            School school=new School();
            school.setclassname(rs.getString("classname"));
            school.setclassteacher(rs.getString("classteacher"));
            school.setclassplace(rs.getString("classplace"));
            list.add(school);
        }
        rs.close();
        pstmt.close();
        conn.close();
    }catch(SQLException e) {
        e.printStackTrace();
    }
    return list;
    
}



    @Override
public boolean delete(String classname) {
boolean flag=false;
try {
    String sql="delete from school where classname='"+classname+"'";
    PreparedStatement pstmt = conn.prepareStatement(sql);
    int i = pstmt.executeUpdate();
    pstmt.close();
    conn.close();
    if(i>0) flag = true;
}catch(SQLException e) {
    System.out.println("刪除失敗");    
    e.printStackTrace();
}

return flag;

}
    public boolean update(String classname,String classteacher,String classplace) {
        
            boolean flag=false;
            try {
                String sql="update school set classteacher='"+classteacher+"',classplace='"+classplace+"' where classname='"+classname+"'";
                PreparedStatement pstmt = conn.prepareStatement(sql);
                int i = pstmt.executeUpdate();
                pstmt.close();
                conn.close();
                if(i>0)flag = true;
            }catch(SQLException e) {
                e.printStackTrace();
            }

            return flag;
            
    }

}

2:在service包中創建StudentService類,在dao包中創建StudentDao類來實現StudentService類中的方法。(具體操作以后更新)

 

6、實現servelet和對應jsp頁面

Servlet有兩種方式創建,一種手工創建。另一種程序自動生成。前者自己創建java類,實現Servlet具體內容,然后需要去WEB_INF下的web.xml去配置servlet  . 而后者則直接由程序替我們配置好了Servlet

1:增

  創建SchoolAddServlet

  

package SchoolAddServlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.SchoolDao;
import dao.SchoolDaoImpl;
import entity.School;


@WebServlet("/SchoolAddServlet")
public class SchoolAddServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

     
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        
        String classname=request.getParameter("classname");
        String classteacher=request.getParameter("classteacher");
        String classplace=request.getParameter("classplace");
        School Subject =new School();
        Subject.setclassname(classname);
        Subject.setclassteacher(classteacher);
        Subject.setclassplace(classplace);
        
        SchoolDao sd = new SchoolDaoImpl();
        try{
            sd.add(Subject);
            response.sendRedirect(request.getContextPath() + "/school.jsp");

        }catch(Exception e){
            System.out.println("添加失敗");
            e.printStackTrace();
        }
        
    }


}

 

  schooladd.jsp頁面部分

  

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div id="addSubjectForm" align="center">
<form action="SchoolAddServlet" method="post">
<tr>
    <td>課程名稱:</td>
    <td><input type="text" name="classname" size="20"></td>
    </tr>
    <tr>
    <td>任課老師:</td>
    <td><input type="text" name="classteacher" size="20"></td>
    </tr>
    <tr>
    <td>上課地點:</td>
    <td><input type="text" name="classplace" size="20"></td>
    </tr>
<tr>
                      <td colspan="2"><div align="center">
                        <input type="submit" value="錄入">    
                    </div>
                </td>
                  </tr>
                  </form>
                  </div>
                  
</body>
</html>

 

action=“SchoolAddServlet”為SubjectAddServlet在web.xml中的URL目錄,即在Servlet中的主類名稱
當在servlet中完成的操作需要獲取頁面表單等的數據時,需要在頁面中指向對應的servlet。

2、刪

  創建SchoolDeleteServlet類

  

package SchoolDeleteServlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.SchoolDao;
import dao.SchoolDaoImpl;
import entity.School;


@WebServlet("/SchoolDelete")
public class SchoolDelete extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
 
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        
        String classname = request.getParameter("classname");
        /*String classteacher=request.getParameter("classteacher");
        String classplace=request.getParameter("classplace");*/
        School school=new School();
        school.setclassname(classname);
        /*school.setclassteacher(classteacher);
        school.setclassplace(classplace);
        */
        SchoolDao sd = new SchoolDaoImpl();
        try {
            sd.delete(classname);
            response.sendRedirect(request.getContextPath() + "/school.jsp");
        }catch(Exception e) {
            System.out.println("刪除失敗");
            e.printStackTrace();
        }

}
}

 

  schooldelete.jsp頁面

  

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div id="addSubjectForm" align="center">
<form action="SchoolDelete" method="post">
<tr>
    <td>課程名稱:</td>
    <td><input type="text" name="classname" size="20"></td>
    </tr>
    <tr>
    <td>任課老師:</td>
    <td><input type="text" name="classteacher" size="20"></td>
    </tr>
    <tr>
    <td>上課地點:</td>
    <td><input type="text" name="classplace" size="20"></td>
    </tr>
<tr>
                      <td colspan="2"><div align="center">
                        <input type="submit" value="刪除">    
                    </div>
                </td>
                  </tr>
                  </form>
                  </div>
</body>
</html>

 

3、改

  創建SchoolUpdate

  

package SchoolUpdate;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.SchoolDao;
import dao.SchoolDaoImpl;
import entity.School;


@WebServlet("/SchoolUpdate")
public class SchoolUpdate extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String classname=request.getParameter("classname");
        String classteacher=request.getParameter("classteacher");
        String classplace=request.getParameter("classplace");
        
        
        SchoolDao sd = new SchoolDaoImpl();
        try{
            sd.update(classname,classteacher,classplace);
            response.sendRedirect(request.getContextPath() + "/school.jsp");

        }catch(Exception e){
            System.out.println("更新失敗");
            e.printStackTrace();
        }
        
    }

}

 

  schoolupdate.jsp頁面

  

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div id="addSubjectForm" align="center">
<form action="SchoolUpdate" method="post">
<tr>
    <td>課程名稱:</td>
    <td><input type="text" name="classname" size="20"></td>
    </tr>
    <tr>
    <td>任課老師:</td>
    <td><input type="text" name="classteacher" size="20"></td>
    </tr>
    <tr>
    <td>上課地點:</td>
    <td><input type="text" name="classplace" size="20"></td>
    </tr>
<tr>
                      <td colspan="2"><div align="center">
                        <input type="submit" value="更改">    
                    </div>
                </td>
                  </tr>
                  </form>
                  </div>
</body>
</html>

 

4、查

  這里需要完成兩個查詢(查詢返回列表;查詢返回列表詳細)

  查詢返回列表:

  SchoolSelect類

  

package SchoolSelect;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.SchoolDao;
import dao.SchoolDaoImpl;
import entity.School;


@WebServlet("/SchoolSelect")
public class SchoolSelect extends HttpServlet {
    private static final long serialVersionUID = 1L;
  
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        SchoolDao sd = new SchoolDaoImpl();
        List<School> list = sd.select();
        request.setAttribute("list", list);
        request.getRequestDispatcher("/schoolselect.jsp").forward(request, response);

    
        
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }


}

注意:當不需要頁面的參數時,頁面由servlet引出

轉發(request.getRequestDispatcher().forward();)和重定向(response.sendRedirect();)區別:

(1).重定向的執行過程:Web服務器向瀏覽器發送一個http響應--》瀏覽器接受此響應后再發送一個新的http請求到服務器--》服務器根據此請求尋找資源並發送給瀏覽器。它可以重定向到任意URL,不能共享request范圍內的數據。
(2).重定向是在客戶端發揮作用,通過新的地址實現頁面轉向。
(3).重定向是通過瀏覽器重新請求地址,在地址欄中可以顯示轉向后的地址。
(4).轉發過程:Web服務器調用內部方法在容器內部完成請求和轉發動作--》將目標資源發送給瀏覽器,它只能在同一個Web應用中使用,可以共享request范圍內的數據。
(5).轉發是在服務器端發揮作用,通過forward()方法將提交信息在多個頁面間進行傳遞。
(6).轉發是在服務器內部控制權的轉移,客戶端瀏覽器的地址欄不會顯示出轉向后的地址。

  

 

  schoolselect.jsp頁面

  

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<
<div id="manageSubject" align="center"><!--查看試題-->
            <table width="95%" cellspacing="10">
                  <tr align="center">
                    <td>課程名稱</td>
                    <td><input type="text" name="classname" size="20"></td>
                    <td>任課老師</td>
                    <td><input type="text" name="classname" size="20"></td>
                    <td>上課地點</td>
                    <td><input type="text" name="classname" size="20"></td>
                         </tr>
                  
                       
                      
                    <c:forEach var="u" items="${list }">
                        <tr align="center">
                            <td>${u.classname}</td>
                            <td><a href="SchoolSelectclassname?subjectID=${u.classname }">查看</a></td>
                        </tr>
                    </c:forEach>
                 
            </table>
        </div>

</body>
</html>

注意:

這里的順序是,先訪問的是SubjectListServlet,在轉發到此頁面,此頁面的查看和刪除又通過對應的servlet來實現對應的功能。

  查詢返回列表詳細:

  創建Schoolselectclassname

  

package SchoolSelect;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.SchoolDao;
import dao.SchoolDaoImpl;
import entity.School;

/**
 * Servlet implementation class SchoolSelectclassname
 */
@WebServlet("/SchoolSelectclassname")
public class SchoolSelectclassname extends HttpServlet {
    private static final long serialVersionUID = 1L;
       

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        
        SchoolDao sd = new SchoolDaoImpl();
        List<School> list = sd.selectclassname(request.getParameter("classname"));
        request.setAttribute("list", list);
        request.getRequestDispatcher("/schoolshow.jsp").forward(request, response);


    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
        
    }


}

注意:

這個查詢方法需要通過限制條件classname來查詢,不然顯示出來的是所有的數據

 

  schoolshow.jsp頁面

  

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<div id="schoolshow" align="center"><!--顯示試題-->
            <table border="0" cellspacing="10" cellpadding="0">
                  <c:forEach var="u" items="${list }">
                  <tr>
                    <td>課程名稱:</td>
                    <td>${u.classname }</td>
                </tr>
                  <tr>
                    <td>任課老師:</td>
                    <td>${u.classteacher }</td>
                  </tr>
                  <tr>
                    <td>上課地點:</td>
                    <td>${u.classplace }</td>
                  </tr>
                   
                  </c:forEach>
            </table>
            </div>

</body>
</html>

注意:

頁面同樣運用的是EL和jstl表達式

 

 

school.jsp主頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<div id="addSubjectForm" align="center">
                <form action="SubjectAddServlet" method="post">
                <tr>
                <td>課程基本信息管理系統 </td></tr>
                <ul>
                <li><a href="http://localhost:8080/School/schooladd.jsp">課程信息錄入 </a></li>
                <li><a href="http://localhost:8080/School/schoolupdate.jsp">課程信息修改  </a></li>
                <li><a href="http://localhost:8080/School/schooldelete.jsp">刪除課程信息  </a></li>
                <li><a href="http://localhost:8080/School/schoolselect.jsp">查詢課程信息  </a></li>
                </ul>
                </form>
</body>
</html>

 

  

  


免責聲明!

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



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