首页 > 技术文章 > javaweb之连接数据库

yuxuan-light-of-Taihu-Lake 2020-10-22 08:22 原文

最近做完了一个图书系统的增删改查,想着来总结一下这几个月的所学内容。

一.首先你需要在电脑上安装上mysql或者sql server(本文以mysql为例)


mysql官网:MySQL :: Begin Your Download

sql server官网:SQL Server 下载 | Microsoft


二.Bean层

Bean层为数据表对应的Java类,是封装数据的模型,比如添加课程系统,在前台提交的课程信息,后台会对应一个Course类,把课程的信息封装到Course中。在这里,我们写一个course.java。

 1 package Bean;
 2 
 3 public class Course {
 4        //private类,私有方法公开用,安全
 5         private String  teachername;
 6         private String  place;
 7         private String  classname;
 8         /*set和get用于设置和读取Java private变量的方法。
 9                这样子外部程序就不会直接访问程序的变量。
10                只能通过set去设置值,用get去读取值。
11                有利于对外封装。防止外部程序随意修改我们的变量。*/
12         public String getClassname() {
13             return classname;
14         }
15         public void setClassname(String classname) {
16             this.classname = classname;
17         }
18 
19         public String getTeachername() {
20             return teachername;
21         }
22         public void setTeachername(String teachername) {
23             this.teachername = teachername;
24         }
25         public String getPlace() {
26             return place;
27         }
28         public void setPlace(String place) {
29             this.place = place;
30         }
31 }

三.dao层

dao层叫数据访问层,全称为data access object,专门负责一些对数据库的访问,属于一种比较底层,比较基础的操作,具体到对于某个表、某个实体的增删改查。此处为增,写一个daoCourse.java。
 1 package dao;
 2 import java.sql.Connection;
 3 import java.sql.PreparedStatement;
 4 import java.sql.SQLException;
 5 import Bean.Course;
 6 import util.DBUtil;
 7 
 8 public class daoCourse {
 9 
10     public boolean add(Course n)
11     {
12         boolean f=false;
13         int a=0;
14         String sql="insert submitcourse(classname,teachername,place) values(?,?,?)";
15         try {
16              Connection conn=DBUtil.getConnection();
17              PreparedStatement pstmt=conn.prepareStatement(sql);
18              pstmt.setString(1,n.getClassname());
19              pstmt.setString(2,n.getTeachername());
20              pstmt.setString(3,n.getPlace());
21               a=pstmt.executeUpdate();
22         } catch (SQLException e) {
23             // TODO Auto-generated catch block
24             e.printStackTrace();
25         }
26         if(a>0) f=true;
27         return f;
28     }
29 }

四.servlet层

servlet是一个java接口,其功能如下(1)创建并返回一个包含基于客户请求性质的动态内容的完整的 HTML 页面。我们建立一个course_servlet.java。
(2)创建可嵌入到现有 HTML 页面中的一部分 HTML 页面( HTML 片段)。
(3)与其它服务器资源(包括数据库和基于 Java 的应用程序)进行通信。

 

package servlet;

import java.io.IOException;
import java.util.ArrayList;
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 Bean.Course;
import dao.daoCourse;

/**
 * Servlet implementation class course_servlet
 */
@WebServlet("/course_servlet")
public class course_servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       daoCourse gooddao=new daoCourse();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public course_servlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String teachername=request.getParameter("teachername");
        String classname=request.getParameter("classname");
        String place=request.getParameter("place");
        Course n=new Course(classname,teachername,place);
        gooddao.add(n);
        request.setAttribute("message", "添加成功");
        request.getRequestDispatcher("NewFile2.jsp").forward(request, response);            
}

 

 五.util层

util用于连接数据库,我们写一个DBUtil.java。

package util;

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

public class DBUtil {
    public static Connection getConnection() {
        //1.添加mysql的驱动jar包到项目中的WebContent/WEB-INF/lib
        
        //2.如何连接数据库?
        Connection conn=null;
     try {
        //加载数据库jar包的驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //连接数据库
        conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/submitcourse?serverTimezone=UTC", "root", "123456");
        System.out.println("连接成功!");
        
        //3.如何操作数据库里的数据
        //定义sql语句
        
        //执行sql语句
        
        //获取sql语句执行器
        
        //处理结果
        
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return conn;
    }
    public static void main(String[] args) {
        DBUtil.getConnection();
    }
     public static void close(Connection connection ) {
         try {
             if (connection != null) {
                 connection.close();
             }

         } catch (SQLException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
     public static void close(PreparedStatement preparedStatement ) {
         try {
             if (preparedStatement != null) {
                 preparedStatement.close();
             }

         } catch (SQLException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
     public static void close(ResultSet resultSet ) {
         try {
             if (resultSet != null) {
                 resultSet.close();
             }

         } catch (SQLException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }

}

六.写jsp


 

 

 

 1.NewFile.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加课程</title>
</head>
<body>
<form action="course_servlet" method="post">
课程名称:<input type="text" id="classname" name="classname"><br>
教师姓名:<input type="text" id="teachername" name="teachername"><br>
教学地点:<input type="text" id="place" name="place"><br>
<input type="submit" value="添加">
</form>
</body>
</html>

2.NewFile2.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>
<%
    Object message = request.getAttribute("message");
    if(message!=null && !"".equals(message)){

%>
<script type="text/javascript">
    alert("<%=request.getAttribute("message")%>");
</script>
<%} %>

<h1>添加成功</h1>


</body>
</html>

七.数据库表

 

 八.运行结果

 

 

 

 

 

 

 


 

 以上是关于课程添加并连接数据库所呈现的内容,接下来会继续给大家更新删改查。

推荐阅读