摘要:这篇Java开发技术栏目下的“JavaWeb JDBC + MySql 通讯录实现简单的增删改查功能案例详解”,介绍的技术点是“javaweb、MySQL、增删改查、JDBC、增删改、通讯录”,希望对大家开发技术学习和问题解决有帮助。
本文实例讲述了JavaWeb JDBC + MySql 通讯录实现简单的增删改查功能。分享给大家供大家参考,具体如下:
开发工具:Eclipse + Navicat
一、新建项目
在Eclipse中新建一个Web项目,至于如何新建Web项目以及如何添加Tomcat服务器的就不赘述了,项目的目录如下
最终实现的效果如下所示:
点击新增可以进行联系人的新增,点击修改/删除可以进行 联系人的修改和删除
部分代码如下
数据库连接:在测试数据库连接时,需要注意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%; } 新增小伙伴 序号姓名年龄电话生日爱好操作${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 + "/"; %> 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 + "/"; %> href="https://cdn.bootcss.com/foundation/5.5.3/css/foundation.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" > 姓名 年龄 电话 生日 爱好 希望本文所述对大家java程序设计有所帮助。