【JDBC】实战 养老中心护理项目的增删改查
在进行jdbc项目之前,我们需要进行mysql的nurse_content表形式如下所示:

进行jdbc项目需要分为四层,分别命名为dao层,pojo层,service层,test层,在dao层中我们主要进行数据库的连接和增删改查主要方法体的书写。pojo层中是保存用户,护理等级和护理内容的字段。service层是写方法名,等待主菜单view类的调用。test类则是测试整个项目的运行,新建两个类,分别是view和start,在view类中进行整个项目菜单框架的书写,在start类中使用main方法启动项目。
下面展示BaseDao和ConnectionDB两类,读者在阅读时只需修改自己的mysql账号和密码,确保可以正确连接自己的mysql。
下面展示BaseDao:
package com.dao;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;public abstract class BaseDao<T> {public boolean batch(String sql, List<Object[]> list) {Connection conn = ConnectionDB.getConnection();PreparedStatement pst = null;try {conn.setAutoCommit(false);pst = conn.prepareStatement(sql);for (int i = 0; i < list.size(); i++) {for (int j = 0; j < list.get(i).length; j++) {pst.setObject(j + 1, list.get(i)[j]);}pst.addBatch();}int row = pst.executeBatch().length;conn.commit();if (row != 0) {return true;}} catch (SQLException e) {// TODO Auto-generated catch blocktry {conn.rollback();} catch (SQLException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}e.printStackTrace();} finally {ConnectionDB.closeConnection(pst, conn);}return false;}public boolean update(String sql, Object[] arr) {int row = 0;Connection conn = ConnectionDB.getConnection();PreparedStatement pst = null;try {pst = conn.prepareStatement(sql);for (int i = 0; i < arr.length; i++) {pst.setObject(i + 1, arr[i]);}row = pst.executeUpdate();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {ConnectionDB.closeConnection(pst, conn);}if (row != 0) {return true;}return false;}public List<T> findMultiple(String sql, Object[] arr) {List<T> list = new ArrayList<T>();Connection conn = ConnectionDB.getConnection();PreparedStatement pst = null;T t = null;try {pst = conn.prepareStatement(sql);if (arr != null) {for (int i = 0; i < arr.length; i++) {pst.setObject(i + 1, arr[i]);}}ResultSet rs = pst.executeQuery();while (rs.next()) {t = this.rowMapper(rs);list.add(t);}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {ConnectionDB.closeConnection(pst, conn);}return list;}public T find(String sql, Object[] arr) {List<T> list = new ArrayList<T>();Connection conn = ConnectionDB.getConnection();PreparedStatement pst = null;T t = null;try {pst = conn.prepareStatement(sql);for (int i = 0; i < arr.length; i++) {pst.setObject(i + 1, arr[i]);}ResultSet rs = pst.executeQuery();if (rs.next()) {t = this.rowMapper(rs);}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {ConnectionDB.closeConnection(pst, conn);}return t;}public abstract T rowMapper(ResultSet rs);// public abstract T rowMapperVo(ResultSet rs);public static void main(String[] args) {}
}
下面展示ConnectionDB:
package com.dao;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;public class ConnectionDB {/*** @Title:getConnection* @Description:TODO* @param @return* @return Connection* @throws**/public static Connection getConnection() {Connection conn = null;try {Class.forName("com.mysql.cj.jdbc.Driver");String url = "jdbc:mysql://localhost:3306/yyzx?useUnicode=true&characterEncoding=UTF-8";String user = "root";String password = "123456";conn = DriverManager.getConnection(url, user, password);} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return conn;}/*** @Title:closeConnection* @Description:TODO* @param @param st* @param @param conn* @return void* @throws**/public static void closeConnection(Statement st,Connection conn) {if(st!=null) {try {st.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(conn!=null) {try {conn.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
注意!!读者在阅读ConnectionDB类时,注意修改自己的用户名,密码以及数据库名称!!例如,在String url中,localhost 3306/后,yyzx是此数据库名,String user:"root",String password:"123456"分别是作者的用户名和密码,请读者自行修改!
下面展示NurseContentDao类
package com.dao;import com.pojo.NurseContent;import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;public class NurseContentDao extends BaseDao<NurseContent>{@Overridepublic NurseContent rowMapper(ResultSet rs){NurseContent content = new NurseContent();try {content.setId(rs.getInt("id"));content.setSerialNumber(rs.getString("serial_number"));content.setNursingName(rs.getString("nursing_name"));content.setServicePrice(rs.getString("service_price"));content.setMessage(rs.getString("message"));content.setStatus(rs.getInt("status"));content.setExecutionCycle(rs.getString("execution_cycle"));content.setExecutionTimes(rs.getString("execution_times"));} catch (SQLException e) {throw new RuntimeException(e);}return content;}//添加护理项目的方法public int addNurseContent(NurseContent content){String sql = "INSERT INTO nursecontent(serial_number,nursing_name,service_price,"+ "message,execution_cycle,execution_times,status,is_deleted) VALUES(?,?,?,?,?,?,?,0)";Object[] arr = {content.getSerialNumber(),content.getNursingName(),content.getServicePrice(),content.getMessage(),content.getExecutionCycle(),content.getExecutionTimes(),content.getStatus()};if (this.update(sql, arr)){return 1;}else{return 0;}}//删除护理项目的方法public int deleteNurseContent(int id){String sql = "DELETE FROM nursecontent where id = ?";Object[] arr = {id};if (this.update(sql, arr)){return 1;}else {return 0;}}//查询所有护理项目的方法public List<NurseContent> searchAll(){String sql = "select id,serial_number,nursing_name,service_price,message,status,"+ "execution_cycle,execution_times from nursecontent " + "where is_deleted is null or is_deleted = 0";return this.findMultiple(sql, null);}//修改护理项目的方法public int updateNurseContent(NurseContent content){String sql = "UPDATE nursecontent SET serial_number = ?,nursing_name = ?,service_price = ?,"+ "message = ?,execution_cycle = ?,execution_times = ?,status = ? WHERE id = ?";Object[] arr = {content.getSerialNumber(),content.getNursingName(),content.getServicePrice(),content.getMessage(),content.getExecutionCycle(),content.getExecutionTimes(),content.getStatus(),content.getId()};if (this.update(sql, arr)){return 1;}else {return 0;}}
}
继承BaseDao,同时重写rowMapper方法,使得我们能够书写增删改查方法,添加方法中sql语句的?作用是暂时占位,真正的值使用get方法获取,若成功返回1,不成功返回0。
下面展示NurseContent类,保存护理项目的字段和getter and setter方法
package com.pojo;public class NurseContent {private int id;private String serialNumber;private String nursingName;private String servicePrice;private String message;private int status;private String executionCycle;private String executionTimes;private int isDeleted;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getSerialNumber() {return serialNumber;}public void setSerialNumber(String serialNumber) {this.serialNumber = serialNumber;}public int getIsDeleted() {return isDeleted;}public void setIsDeleted(int isDeleted) {this.isDeleted = isDeleted;}public String getExecutionTimes() {return executionTimes;}public void setExecutionTimes(String exectionTimes) {this.executionTimes = exectionTimes;}public String getExecutionCycle() {return executionCycle;}public void setExecutionCycle(String exectionCycle) {this.executionCycle = exectionCycle;}public int getStatus() {return status;}public void setStatus(int status) {this.status = status;}public String getServicePrice() {return servicePrice;}public void setServicePrice(String servicePrice) {this.servicePrice = servicePrice;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public String getNursingName() {return nursingName;}public void setNursingName(String nursingName) {this.nursingName = nursingName;}
}
下面展示NurseContentService层,书写方法名,使得view菜单可以调用
package com.service;import com.dao.NurseContentDao;
import com.pojo.NurseContent;import java.util.List;public class NurseContentService{private NurseContentDao nurseContentDao = new NurseContentDao();//添加护理项目的方法public int addNurseContent(NurseContent content){return nurseContentDao.addNurseContent(content);}//查询所有护理项目的方法public List<NurseContent> searchAll(){return nurseContentDao.searchAll();}//删除护理项目的方法public int deleteNurseContent(int id){return nurseContentDao.deleteNurseContent(id);}//修改护理项目的方法public int updateNurseContent(NurseContent content){return nurseContentDao.updateNurseContent(content);}
}
最后进行主菜单的书写
package com.test;import com.dao.NurseLevelDao;
import com.pojo.NurseContent;
import com.pojo.NurseLevel;
import com.pojo.User;
import com.service.NurseLevelService;
import com.service.UserService;
import com.service.NurseContentService;
import java.util.List;
import java.util.Scanner;public class View {private UserService userService = new UserService();private NurseLevelService nurseLevelService = new NurseLevelService();private NurseContentService nurseContentService = new NurseContentService();Scanner input = new Scanner(System.in);//系统启动方法public void index() {//需要先登录,如果登陆成功显示功能菜单if(login()){menu();}else {System.out.println("登陆失败");}}//显示功能菜单的方法public void menu(){while (true){System.out.println("\n**********欢迎来到颐养健康中心***************");System.out.println("1 护理级别");System.out.println("--1.1护理级别添加");System.out.println("--1.2护理级别显示");System.out.println("--1.3护理级别修改");System.out.println("--1.4护理级别删除");System.out.println();System.out.println("2 护理项目");System.out.println("--2.1护理项目添加");System.out.println("--2.2护理项目显示");System.out.println("--2.3护理项目修改");System.out.println("--2.4护理项目删除");System.out.println();System.out.println("3 退出系统");System.out.println("\n*****************************************");System.out.println("请选择:");String choice = input.next();switch (choice){case "1.1" ://此处调用护理级别添加的方法。addNurseLevel();break;case "1.2" :showNurseLevel();break;case "1.3" :editNurseLevel();break;case "1.4" :deleteNurseLevel();break;case "2.1" :addNurseContent();break;case "2.2" :showNurseContent();break;case "2.3" :editNurseContent();break;case "2.4" :deleteNurseContent();break;case "3" :System.out.println("退出系统");return;default:System.out.println("输入错误,请重新输入");break;}}}//添加护理级别的方法public void addNurseLevel(){System.out.print("请输入护理等级名称:");NurseLevel level = new NurseLevel();level.setLevelName(input.next());System.out.print("请输入护理等级状态(1启用2停用):");level.setLevelStatus(input.nextInt());//调用业务层添加护理等级的方法nurseLevelService.addNurseLevel(level);System.out.println("护理级别添加成功");}//删除护理级别的方法public void deleteNurseLevel(){System.out.print("请输入要删除的护理等级编号:");nurseLevelService.deleteNurseLevel(input.nextInt());System.out.println("护理级别删除成功");}//修改护理级别的方法public void editNurseLevel(){NurseLevel level = new NurseLevel();System.out.print("请输入修改的护理等级编号:");level.setId(input.nextInt());System.out.print("请输入修改的护理等级名称:");level.setLevelName(input.next());System.out.print("请输入修改的护理等级状态(1启用2停用):");level.setLevelStatus(input.nextInt());//调用业务层修改护理级别信息nurseLevelService.updateNurseLevel(level);System.out.println("护理级别修改成功");}//显示所有护理级别的方法public void showNurseLevel(){List<NurseLevel> levels = nurseLevelService.searchAll();System.out.println("编号\t护理等级名称\t护理状态");for (NurseLevel nurseLevel : levels) {System.out.println(nurseLevel.getId()+"\t"+nurseLevel.getLevelName()+"\t"+nurseLevel.getLevelStatus());}}public boolean login(){System.out.print("请输入用户名:");String username = input.next();System.out.print("请输入密码:");String password = input.next();User user = userService.searchByUnameAndPwd(username,password);if (user != null){return true;}else {return false;}}//显示所有护理项目的方法public void showNurseContent(){List<NurseContent> contents = nurseContentService.searchAll();System.out.println("序号\t项目编号\t价格\t执行周期\t执行次数\t执行时间\t状态");for(NurseContent content : contents){System.out.println(content.getId() + "\t" + content.getSerialNumber()+ "\t" + content.getServicePrice() + "\t" + content.getExecutionCycle()+ "\t" + content.getExecutionTimes() + "\t" + content.getStatus() + "\t"+ content.getMessage());}}//添加护理项目的方法public void addNurseContent(){NurseContent content = new NurseContent();System.out.print("请输入护理项目的序列号:");content.setSerialNumber(input.next());System.out.print("请输入护理项目的名称:");content.setNursingName(input.next());System.out.print("请输入护理项目的价格:");content.setServicePrice(input.next());System.out.print("请输入护理项目的备注:");content.setMessage(input.next());System.out.print("请输入护理项目的执行周期:");content.setExecutionTimes(input.next());System.out.print("请输入护理项目的执行次数:");content.setExecutionCycle(input.next());System.out.print("请输入护理项目的状态:");content.setStatus(input.nextInt());//调用业务层添加护理项目的方法nurseContentService.addNurseContent(content);System.out.println("护理项目添加成功!");}//修改护理项目的方法public void editNurseContent(){NurseContent content = new NurseContent();System.out.print("请输入修改的护理项目编号:");content.setId(input.nextInt());System.out.print("请输入修改的护理项目的序列号:");content.setSerialNumber(input.next());System.out.print("请输入修改的护理项目的名称:");content.setNursingName(input.next());System.out.print("请输入修改的护理项目的价格:");content.setServicePrice(input.next());System.out.print("请输入修改的护理项目的备注:");content.setMessage(input.next());System.out.print("请输入修改的护理项目的执行周期:");content.setExecutionTimes(input.next());System.out.print("请输入修改的护理项目的执行次数:");content.setExecutionCycle(input.next());System.out.print("请输入修改的护理项目的状态:");content.setStatus(input.nextInt());nurseContentService.updateNurseContent(content);System.out.println("护理项目修改成功!");}public void deleteNurseContent(){System.out.print("请输入要删除的护理项目编号:");nurseContentService.deleteNurseContent(input.nextInt());System.out.println("护理项目删除成功!");}
}
主菜单包含护理项目和护理等级,本文章只涉及护理项目的内容,测试项目时也只测试护理项目
展示start类:
package com.test;public class Start {public static void main(String[] args) {View view = new View();view.index();}}
展示项目运行:







项目运行成功。
