热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

javaweb增删查改mysql_JavaWebJDBC+MySql通讯录实现简单的增删改查功能案例详解

摘要:这篇Java开发技术栏目下的“JavaWebJDBCMySql通讯录实现简单的增删改查功能案例详解”,介绍的技术点是“javaweb、MySQL、

摘要:这篇Java开发技术栏目下的“JavaWeb JDBC + MySql 通讯录实现简单的增删改查功能案例详解”,介绍的技术点是“javaweb、MySQL、增删改查、JDBC、增删改、通讯录”,希望对大家开发技术学习和问题解决有帮助。

本文实例讲述了JavaWeb JDBC + MySql 通讯录实现简单的增删改查功能。分享给大家供大家参考,具体如下:

开发工具:Eclipse + Navicat

一、新建项目

在Eclipse中新建一个Web项目,至于如何新建Web项目以及如何添加Tomcat服务器的就不赘述了,项目的目录如下

10886285cb5d1b149178e0d23592e06f.png

最终实现的效果如下所示:

3fdfce2f1906ce20826ed8ad8f563d16.png

点击新增可以进行联系人的新增,点击修改/删除可以进行 联系人的修改和删除

部分代码如下

数据库连接:在测试数据库连接时,需要注意mysql 时区的设置,安装mysql时默认的时区时美国时间,与本地相差8个小时,所以如果不修改则在链接数据库时会报错。

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 {

// 加载数据库驱动

Class.forName(DRIVER);

// 获得数据库连接

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

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

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();

}

}

}

联系人:

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;

}

}

增删改查的实现:

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 GetAllContact(){

List 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 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("");

}

if(dos.equals("del")) {

String ids = request.getParameter("id");

int id = Integer.parseInt(ids);

ud.DeleteContact(id);

out.print("");

}

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("");

}

catch(ParseException ex) {

ex.printStackTrace();

}

}

}

}

JSP页面

index 页面,此页面需要添加 jstl.jar 和standard.jar ,否则无法引用 taglib

String path = request.getContextPath();

String basePath = request.getScheme() + "://"

+ request.getServerName() + ":" + request.getServerPort()

+ path + "/";

//下面的语句初始为初始化页面,如果不加下面语句访问主页不会显示数据库中保存的数据

ContactService ud = new ContactService();

List ulist = ud.GetAllContact();

request.setAttribute("ulist", ulist);

%>

href="https://cdn.bootcss.com/foundation/5.5.3/css/foundation.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" >

table {

margin: auto;

}

td {

text-align: center;

}

h1 {

margin-left: 40%;

}

a#add {

margin-left: 45%;

}

Insert title here通讯录主页

新增小伙伴

序号姓名年龄电话生日爱好操作${U.id}${U.name}${U.age}${U.phone}${U.date}${U.favorite}修改 删除

标签遍历List--%>

Add页面

String path = request.getContextPath();

String basePath = request.getScheme() + "://"

+ request.getServerName() + ":" + request.getServerPort()

+ path + "/";

%>

My JSP 'add.jsp' starting page

href="https://cdn.bootcss.com/foundation/5.5.3/css/foundation.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" >

新增页面

姓名

年龄

电话

生日

爱好

Edit页面

String path = request.getContextPath();

String basePath = request.getScheme() + "://"

+ request.getServerName() + ":" + request.getServerPort()

+ path + "/";

%>

My JSP 'add.jsp' starting page

href="https://cdn.bootcss.com/foundation/5.5.3/css/foundation.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" >

修改页面

姓名

年龄

电话

生日

爱好

希望本文所述对大家java程序设计有所帮助。



推荐阅读
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • PHP设置MySQL字符集的方法及使用mysqli_set_charset函数
    本文介绍了PHP设置MySQL字符集的方法,详细介绍了使用mysqli_set_charset函数来规定与数据库服务器进行数据传送时要使用的字符集。通过示例代码演示了如何设置默认客户端字符集。 ... [详细]
  • 本文介绍了在Mac上搭建php环境后无法使用localhost连接mysql的问题,并通过将localhost替换为127.0.0.1或本机IP解决了该问题。文章解释了localhost和127.0.0.1的区别,指出了使用socket方式连接导致连接失败的原因。此外,还提供了相关链接供读者深入了解。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • Nginx使用(server参数配置)
    本文介绍了Nginx的使用,重点讲解了server参数配置,包括端口号、主机名、根目录等内容。同时,还介绍了Nginx的反向代理功能。 ... [详细]
  • 本文介绍了如何使用php限制数据库插入的条数并显示每次插入数据库之间的数据数目,以及避免重复提交的方法。同时还介绍了如何限制某一个数据库用户的并发连接数,以及设置数据库的连接数和连接超时时间的方法。最后提供了一些关于浏览器在线用户数和数据库连接数量比例的参考值。 ... [详细]
  • 原文地址:https:www.cnblogs.combaoyipSpringBoot_YML.html1.在springboot中,有两种配置文件,一种 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 本文介绍了使用postman进行接口测试的方法,以测试用户管理模块为例。首先需要下载并安装postman,然后创建基本的请求并填写用户名密码进行登录测试。接下来可以进行用户查询和新增的测试。在新增时,可以进行异常测试,包括用户名超长和输入特殊字符的情况。通过测试发现后台没有对参数长度和特殊字符进行检查和过滤。 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • 本文详细介绍了MysqlDump和mysqldump进行全库备份的相关知识,包括备份命令的使用方法、my.cnf配置文件的设置、binlog日志的位置指定、增量恢复的方式以及适用于innodb引擎和myisam引擎的备份方法。对于需要进行数据库备份的用户来说,本文提供了一些有价值的参考内容。 ... [详细]
  • 本文介绍了高校天文共享平台的开发过程中的思考和规划。该平台旨在为高校学生提供天象预报、科普知识、观测活动、图片分享等功能。文章分析了项目的技术栈选择、网站前端布局、业务流程、数据库结构等方面,并总结了项目存在的问题,如前后端未分离、代码混乱等。作者表示希望通过记录和规划,能够理清思路,进一步完善该平台。 ... [详细]
  • Tomcat/Jetty为何选择扩展线程池而不是使用JDK原生线程池?
    本文探讨了Tomcat和Jetty选择扩展线程池而不是使用JDK原生线程池的原因。通过比较IO密集型任务和CPU密集型任务的特点,解释了为何Tomcat和Jetty需要扩展线程池来提高并发度和任务处理速度。同时,介绍了JDK原生线程池的工作流程。 ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
author-avatar
淑圣承琦9_416
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有