欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaWeb JDBC + MySql 通訊錄實(shí)現(xiàn)簡單的增刪改查功能案例詳解

 更新時(shí)間:2019年08月17日 09:37:58   作者:sun_jinhang  
這篇文章主要介紹了JavaWeb JDBC + MySql 通訊錄實(shí)現(xiàn)簡單的增刪改查功能,結(jié)合具體案例形式詳細(xì)分析了JavaWeb JDBC + MySql數(shù)據(jù)庫連接、增刪改查等相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下

本文實(shí)例講述了JavaWeb JDBC + MySql 通訊錄實(shí)現(xiàn)簡單的增刪改查功能。分享給大家供大家參考,具體如下:

開發(fā)工具:Eclipse + Navicat

項(xiàng)目源碼:Github:https://github.com/Sunjinhang/JavaWeb

一、新建項(xiàng)目

在Eclipse中新建一個(gè)Web項(xiàng)目,至于如何新建Web項(xiàng)目以及如何添加Tomcat服務(wù)器的就不贅述了,項(xiàng)目的目錄如下

最終實(shí)現(xiàn)的效果如下所示:

點(diǎn)擊新增可以進(jìn)行聯(lián)系人的新增,點(diǎn)擊修改/刪除可以進(jìn)行 聯(lián)系人的修改和刪除

部分代碼如下

數(shù)據(jù)庫連接:在測(cè)試數(shù)據(jù)庫連接時(shí),需要注意mysql 時(shí)區(qū)的設(shè)置,安裝mysql時(shí)默認(rèn)的時(shí)區(qū)時(shí)美國時(shí)間,與本地相差8個(gè)小時(shí),所以如果不修改則在鏈接數(shù)據(jù)庫時(shí)會(huì)報(bào)錯(cuò)。

package pers.contact.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDao {
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    public static final String URL = "jdbc:mysql://localhost:3306/demo?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=GMT%2B8";
    public static final String USER = "root";
    public static final String PASSWORD = "sasa";
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    public void getConnection() {
        try {
            // 加載數(shù)據(jù)庫驅(qū)動(dòng)
            Class.forName(DRIVER);
            // 獲得數(shù)據(jù)庫連接
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public int executeUpdate(String sql, Object... obj) {
        int num = 0;
        getConnection();
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < obj.length; i++) {
                pstmt.setObject(i + 1, obj[i]);
            }
            num = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return num;
    }
    public ResultSet executeQuery(String sql, Object... obj) {
        getConnection();
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < obj.length; i++) {
                pstmt.setObject(i + 1, obj[i]);
            }
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }
    public void closeAll() {
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

聯(lián)系人:

package pers.contact.entity;
import java.util.Date;
public class Contact {
    public Contact(int id, String name, int age, String phone, Date date, String favorite) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.phone = phone;
        this.date = date;
        this.favorite = favorite;
    }
    private int id;
    private String name;
    private int age;
    private String phone;
    private Date date;
    private String favorite;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
    public String getFavorite() {
        return favorite;
    }
    public void setFavorite(String favorite) {
        this.favorite = favorite;
    }
}

增刪改查的實(shí)現(xiàn):

package pers.contact.service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import pers.contact.entity.Contact;
import pers.contact.dao.BaseDao;;
public class ContactService extends BaseDao {
    ResultSet rs = null;
    public List<Contact> GetAllContact(){
        List<Contact> list = new ArrayList();
        String sql = "select * from contact";
        rs = executeQuery(sql);
        try {
            while (rs.next()) {
                Contact f = new Contact(rs.getInt(1), rs.getString(2),
                        rs.getInt(3), rs.getString(4), rs.getDate(5),
                        rs.getString(6));
                list.add(f);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
    public int AddContact(Contact contact)
    {
        int num = 0;
        String sql = "insert into contact(name,age,phone,date,favorite) values(?,?,?,?,?)";
        try {
            num = executeUpdate(sql, contact.getName(), contact.getAge(), contact.getPhone(),
                    contact.getDate(), contact.getFavorite());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return num;
    }
    public int DeleteContact(int id)
    {
        int num = 0;
        String sql = "delete from contact where id = ?";
        try {
            num = executeUpdate(sql, id);
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
        return num;
    }
    public Contact GetContact(int id) {
        String sql = "select * from contact where id = ?";
        Contact contact = null;
        rs = executeQuery(sql, id);
        try {
            while(rs.next()) {
                contact = new Contact(rs.getInt(1),rs.getString(2),rs.getInt(3),rs.getString(4),rs.getDate(5),rs.getString(6));
            }
        }
        catch(SQLException ex){
            ex.printStackTrace();
        }
        return contact;
    }
    public int UpdateContact(Contact contact) {
        int num = 0;
        String sql = "update contact set name = ?,age = ?,phone = ?,date = ?,favorite = ? where id = ?";
        try {
            num = executeUpdate(sql, contact.getName(),contact.getAge(),contact.getPhone(),contact.getDate(),contact.getFavorite(),contact.getId());
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
        return num;
    }
}

Servlet:

package pers.contact.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
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 javax.servlet.http.HttpSession;
import pers.contact.entity.Contact;
import pers.contact.service.ContactService;
/**
 * Servlet implementation class ContactServlet
 */
@WebServlet("/ContactServlet")
public class ContactServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
  /**
   * @see HttpServlet#HttpServlet()
   */
  public ContactServlet() {
    super();
    // TODO Auto-generated constructor stub
  }
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        PrintWriter out = response.getWriter();
        ContactService ud = new ContactService();
        // 獲得do屬性
        String dos = request.getParameter("do");
        if (dos == null || dos.equals("")) {
            dos = "index";
        }
        // 主頁
        if (dos.equals("index")) {
            List<Contact> ulist = ud.GetAllContact();
            request.setAttribute("ulist", ulist);
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }
        if(dos.equals("add")) {
            String name = request.getParameter("name");
            int age = Integer.parseInt(request.getParameter("age"));
            String phone = request.getParameter("phone");
            String dates = request.getParameter("date");
            SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
            Date date = null;
            try {
                date = (Date)sdf.parse(dates);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //愛好獲取
            String favorite = request.getParameter("favorite");
            Contact contact = new Contact(0,name,age,phone,date,favorite);
            ud.AddContact(contact);
            out.print("<script>alert('新增成功!');window.location='ContactServlet?do=index';</script>");
        }
        if(dos.equals("del")) {
            String ids = request.getParameter("id");
            int id = Integer.parseInt(ids);
            ud.DeleteContact(id);
            out.print("<script>alert('刪除成功!');window.location='ContactServlet?do=index';</script>");
        }
        if(dos.equals("editbefore")) {
            int id = Integer.parseInt(request.getParameter("id"));
            Contact f = ud.GetContact(id);
            session.setAttribute("edituser", f);
            response.sendRedirect("edit.jsp");
            return;
        }
        if(dos.equals("edit")) {
            try {
                int id = Integer.parseInt(request.getParameter("id"));
                String name = request.getParameter("name");
                int age = Integer.parseInt(request.getParameter("age"));
                String phone = request.getParameter("phone");
                String dates = request.getParameter("date");
                SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
                Date date = null;
                date = (Date)sdf.parse(dates);
                String favorite = request.getParameter("favorite");
                Contact contact = new Contact(id,name,age,phone,date,favorite);
                ud.UpdateContact(contact);
                out.print("<script>alert('修改成功!');window.location='ContactServlet?do=index';</script>");
            }
            catch(ParseException ex) {
                ex.printStackTrace();
            }
        }
    }
}

JSP頁面

index 頁面,此頁面需要添加 jstl.jar 和standard.jar ,否則無法引用 taglib

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="pers.contact.entity.Contact"%>
<%@ page import="pers.contact.service.ContactService"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
    //下面的語句初始為初始化頁面,如果不加下面語句訪問主頁不會(huì)顯示數(shù)據(jù)庫中保存的數(shù)據(jù)
    ContactService ud = new ContactService();
    List<Contact> ulist = ud.GetAllContact();
    request.setAttribute("ulist", ulist);
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<meta charset="ISO-8859-1">
<link rel="stylesheet"
     rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script
    src="https://cdn.bootcss.com/foundation/5.5.3/js/foundation.min.js"></script>
<script
    src="https://cdn.bootcss.com/foundation/5.5.3/js/vendor/modernizr.js"></script>
<style type="text/css">
table {
    margin: auto;
}
td {
    text-align: center;
}
h1 {
    margin-left: 40%;
}
a#add {
    margin-left: 45%;
}
</style>
<title>Insert title here</title>
</head>
<body style="padding:20px;">
    <h1>通訊錄主頁</h1>
    <a id="add" href="add.jsp" rel="external nofollow" >新增小伙伴</a>
    <table>
        <thead>
            <tr>
                <th>序號(hào)</th>
                <th>姓名</th>
                <th>年齡</th>
                <th>電話</th>
                <th>生日</th>
                <th>愛好</th>
                <th>操作</th>
            </tr>
            <c:forEach var="U" items="${ulist}">
            <tr>
                <th>${U.id}</th>
                <th>${U.name}</th>
                <th>${U.age}</th>
                <th>${U.phone}</th>
                <th>${U.date}</th>
                <th>${U.favorite}</th>
                <th><a href="ContactServlet?do=editbefore&id=${U.id}" rel="external nofollow" >修改</a> <a href="ContactServlet?do=del&id=${U.id}" rel="external nofollow" >刪除</a> </th>
            </tr>
            </c:forEach>
        </thead>
        <%--<c:forEach/>標(biāo)簽遍歷List--%>
    </table>
</body>
</html>

Add頁面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<title>My JSP 'add.jsp' starting page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
     rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script
    src="https://cdn.bootcss.com/foundation/5.5.3/js/foundation.min.js"></script>
<script
    src="https://cdn.bootcss.com/foundation/5.5.3/js/vendor/modernizr.js"></script>
</head>
<body>
    <h1>新增頁面</h1>
<form action="ContactServlet?do=add" method="post" style="width:50%;">
  <fieldset>
  <label>姓名 <input type="text" placeholder="name" required="required" name="name" /> </label>
  <label>年齡 <input type="number" placeholder="age" required="required" min="1" max="133" name="age" /> </label>
  <label>電話<input type="text" placeholder="phonenum" required="required" name="phone" /> </label>
  <label>生日<input type="date" placeholder="date" required="required" name="date" /> </label>
  <label>愛好<input type="text" placeholder="favorite" required="required" name="favorite" /> </label>
  <input type="submit" value="新增" class="button" />
  <input type="reset" class="button" />
  </fieldset>
 </form>
</body>
</html>

Edit頁面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<title>My JSP 'add.jsp' starting page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
     rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script
    src="https://cdn.bootcss.com/foundation/5.5.3/js/foundation.min.js"></script>
<script
    src="https://cdn.bootcss.com/foundation/5.5.3/js/vendor/modernizr.js"></script>
</head>
<body>
    <h1>修改頁面</h1>
    <form action="ContactServlet?do=edit&id=${edituser.id}" method="post" style="width:50%">
        <fieldset>
            <label>姓名 <input type="text" placeholder="name" name="name" value = "${edituser.name}">
            </label>
            <label>年齡 <input type="text" placeholder="age" name="age" value = "${edituser.age}">
            </label>
            <label>電話<input type="text" placeholder="phone" name="phone" value = "${edituser.phone}">
            </label>
            <label>生日<input type="date" placeholder="date" name="date" value = "${edituser.date}">
            </label>
            <label>愛好<input type="text" placeholder="favorite" name="favorite" value = "${edituser.favorite}">
            </label>
            <input type="submit" value="修改" class="button"> <input type="reset" class="button">
        </fieldset>
    </form>
</body>
</html>

更多java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java面向?qū)ο蟪绦蛟O(shè)計(jì)入門與進(jìn)階教程》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總

希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • MyBatis批量插入的五種方式小結(jié)(MyBatis以集合方式批量新增)

    MyBatis批量插入的五種方式小結(jié)(MyBatis以集合方式批量新增)

    本文主要介紹了MyBatis批量插入的五種方式小結(jié)(MyBatis以集合方式批量新增),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-01-01
  • java 中newInstance()方法和new關(guān)鍵字的區(qū)別

    java 中newInstance()方法和new關(guān)鍵字的區(qū)別

    這篇文章主要介紹了java 中newInstance()方法和new關(guān)鍵字的區(qū)別的相關(guān)資料,希望通過本文大家能掌握他們之家的區(qū)別與用法,需要的朋友可以參考下
    2017-09-09
  • 新手必備的IDEA常用設(shè)置總結(jié)

    新手必備的IDEA常用設(shè)置總結(jié)

    今天給大家總結(jié)了一些IDEA的常用設(shè)置,文中有非常詳細(xì)的圖文介紹,對(duì)正在學(xué)習(xí)使用IDEA的小伙伴們很有幫助,需要的朋友可以參考下
    2021-05-05
  • java之lombok的構(gòu)建者模式Builder中的泛型寫法說明

    java之lombok的構(gòu)建者模式Builder中的泛型寫法說明

    這篇文章主要介紹了java之lombok的構(gòu)建者模式Builder中的泛型寫法說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-01-01
  • 如何使用Spring工具類動(dòng)態(tài)匹配url

    如何使用Spring工具類動(dòng)態(tài)匹配url

    這篇文章主要介紹了如何使用Spring工具類動(dòng)態(tài)匹配url,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • 基于Springboot實(shí)現(xiàn)定時(shí)發(fā)送郵件功能

    基于Springboot實(shí)現(xiàn)定時(shí)發(fā)送郵件功能

    這篇文章主要為大家詳細(xì)介紹了基于Springboot實(shí)現(xiàn)定時(shí)發(fā)送郵件功能的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-03-03
  • Java觀察者模式之實(shí)現(xiàn)對(duì)象間的一對(duì)多依賴

    Java觀察者模式之實(shí)現(xiàn)對(duì)象間的一對(duì)多依賴

    這篇文章主要介紹了Java觀察者模式之實(shí)現(xiàn)對(duì)象間的一對(duì)多依賴的方法,Java觀察者模式是一種行為型設(shè)計(jì)模式,用于實(shí)現(xiàn)對(duì)象之間的消息傳遞和通信,文中有詳細(xì)的實(shí)現(xiàn)步驟和代碼示例,,需要的朋友可以參考下
    2023-05-05
  • Java中關(guān)鍵字final finally finalize的區(qū)別介紹

    Java中關(guān)鍵字final finally finalize的區(qū)別介紹

    這篇文章主要給大家分享的是 Java中final,finally,finalize 到底有什么區(qū)別,文章圍繞final,finally,finalize的相關(guān)資料展開詳細(xì)內(nèi)容,具有一定的參考的價(jià)值,需要的朋友可以參考一下
    2022-04-04
  • MyBatis自定義SQL攔截器示例詳解

    MyBatis自定義SQL攔截器示例詳解

    Mybatis支持對(duì)Executor、StatementHandler、PameterHandler和ResultSetHandler 接口進(jìn)行攔截,也就是說會(huì)對(duì)這4種對(duì)象進(jìn)行代理,下面這篇文章主要給大家介紹了關(guān)于MyBatis自定義SQL攔截器的相關(guān)資料,需要的朋友可以參考下
    2021-10-10
  • Java實(shí)現(xiàn)爬蟲給App提供數(shù)據(jù)(Jsoup 網(wǎng)絡(luò)爬蟲)

    Java實(shí)現(xiàn)爬蟲給App提供數(shù)據(jù)(Jsoup 網(wǎng)絡(luò)爬蟲)

    這篇文章主要介紹了Java實(shí)現(xiàn)爬蟲給App提供數(shù)據(jù),即Jsoup 網(wǎng)絡(luò)爬蟲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-01-01

最新評(píng)論