基于JDBC和Druid的CMS客户管理系统实操案例

1. 客户表

CREATE TABLE t_customer(
  id INT PRIMARY KEY AUTO_INCREMENT COMMENT '客户主键',
  name VARCHAR(20)  COMMENT '客户名称',
  gender VARCHAR(4) COMMENT '客户性别',
  age INT  COMMENT '客户年龄',
  salary DOUBLE(8,1) COMMENT '客户工资',
  phone VARCHAR(11) COMMENT '客户电话')

2. 项目结构

在这里插入图片描述

2.1 JavaBean

Customer.java

package com.atguigu.cms.javabean;

public class Customer {

    private int id;
    private String name;// : 姓名
    private String gender; // 性别
    private int age;// : 年龄
    private double salary;// : 工资
    private String phone; // 电话

    public Customer() {}

    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 double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return id + "\t" + name + (name.length() < 3 ? "\t\t" : "\t") + gender + "\t\t" + age + "\t\t" + salary + "\t\t" + phone;
    }
}

2.2 封装的JDBCUTILS

JdbcUtil.java

package com.atguigu.cms.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Title: JdbcUtil
 * @Package: com.atguigu.cms.utils
 * @Description: 将JDBC标准操作步骤中的注册驱动、获取连接、释放连接功能进行封装
 * @Author: untifa
 * @Date: 2023/3/26 - 12:07
 */
public class JdbcUtil {

    private static DataSource dataSource = null;
    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();


    static {

        Properties properties = new Properties();
        InputStream resourceAsStream = JdbcUtil.class.getClassLoader().getResourceAsStream("druid.properties");

        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        try {
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }



    public static Connection getConnection() throws SQLException {

        if (tl.get() == null) {
            Connection connection = dataSource.getConnection();
            tl.set(connection);
        }
        return tl.get();
    }

    public static void freeConnection() throws SQLException {
        Connection connection = tl.get();
        if (connection != null) {
            tl.remove();
        }
        connection.setAutoCommit(true);
        connection.close();
    }
}

BaseDao.java

package com.atguigu.cms.utils;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Title: BaseDao
 * @Package: com.atguigu.cms.utils
 * @Description: 将JDBC标准操作步骤中的执行DQL并获取返回信息、执行非DQL并获取返回信息功能进行封装
 * @Author: untifa
 * @Date: 2023/3/26 - 12:08
 */
public class BaseDao {

    public int update(String sql, Object... params) throws SQLException {

        Connection connection = JdbcUtil.getConnection();

        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        for (int i = 0; i < params.length; i++) {

            preparedStatement.setObject(i + 1, params[i]);

        }

        int rows = preparedStatement.executeUpdate();

        preparedStatement.close();

        if (connection.getAutoCommit()) {

            JdbcUtil.freeConnection();

        }

        return rows;

    }

    public <T> List<T> query(Class<T> clazz, String sql, Object... params) throws Exception {

        Connection connection = JdbcUtil.getConnection();

        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        for (int i = 0; i < params.length; i++) {

            preparedStatement.setObject(i + 1, params[i]);

        }

        ResultSet resultSet = preparedStatement.executeQuery();

        ResultSetMetaData metaData = preparedStatement.getMetaData();

        int columnCount = metaData.getColumnCount();

        ArrayList<T> list = new ArrayList<T>();

        while (resultSet.next()) {

            T t = clazz.newInstance();

            for (int i = 0; i < columnCount; i++) {

                Field declaredField = clazz.getDeclaredField(metaData.getColumnLabel(i+1));
                declaredField.setAccessible(true);
                declaredField.set(t, resultSet.getObject(i+1));

            }

            list.add(t);

        }

        resultSet.close();
        preparedStatement.close();

        if (connection.getAutoCommit()) {

            JdbcUtil.freeConnection();

        }

        return list;

    }

}

2.3 Main程序入口

CustomerManage.java

package com.atguigu.cms.main;

import com.atguigu.cms.view.CustomerView;

public class CustomerManage {

    public static void main(String[] args) {
        CustomerView view = new CustomerView();
        view.enterMainMenu();
    }
}

2.4 UI程序入口

CustomerView.java

package com.atguigu.cms.view;

import com.atguigu.cms.javabean.Customer;
import com.atguigu.cms.service.CustomerService;

import java.util.List;

/**
 * 这是主控模块, 负责菜单显示和用户交互. 也称为UI, 内部要频繁到管理器对象, 所以使用对象关联
 */
public class CustomerView {

    /**
     * 关联到的管理器对象
     */
    private CustomerService customerService = new CustomerService();

    /**
     * 进入主菜单, 是项目的真正入口, 不可以轻易结束
     */
    public void enterMainMenu() {
        // 1) 声明布尔
        boolean loopFlag = true;
        // 2) 写循环
        do {
            System.out.println("\n--------------------------------客户信息管理--------------------------------------\n");
            listAllCustomers();
            System.out.print("1 添加客户 2 修改客户 3 删除客户 4 客户列表 5 退   出  请选择(1 - 5) : ");
            // 读取用户选择
            char choice = KeyboardUtility.readMenuSelection();
            switch (choice) {
                case '1' : addNewCustomer(); break;
                case '2' : modifyCustomer(); break;
                case '3' : deleteCustomer(); break;
                case '4' : listAllCustomers(); break;
                case '5' :
                    System.out.print("确认是否退出(Y/N) : ");
                    // 获取用户输入的确认
                    char confirm = KeyboardUtility.readConfirmSelection();
                    if (confirm == 'Y') {
                        loopFlag = false;
                    }
                    break;
            }
        } while (loopFlag);
    }

    /**
     * 添加新员工
     */
    private void addNewCustomer() {
        Customer customer = new Customer();
        System.out.println("---------------------添加客户---------------------");
        System.out.print("姓名 : ");
        String name = KeyboardUtility.readString(10);
        customer.setName(name);
        System.out.print("性别 : ");
        String gender = KeyboardUtility.readString(1);
        customer.setGender(gender);
        System.out.print("年龄 : ");
        int age = KeyboardUtility.readInt();
        customer.setAge(age);
        System.out.print("工资 : ");
        int salary = KeyboardUtility.readInt();
        customer.setSalary(salary);
        System.out.print("电话 : ");
        String phone = KeyboardUtility.readString(15);
        customer.setPhone(phone);
        // 通过调用管理器对象完成 员工添加
        customerService.addCustomer(customer);
        System.out.println("---------------------添加完成---------------------");
    }

    /**
     * 修改员工
     */
    private void modifyCustomer () {
        System.out.println("---------------------修改客户---------------------");
        System.out.print("请选择待修改客户ID(-1退出) : ");
        // 获取用户输入的id
        int id = KeyboardUtility.readInt();
        if (id == -1) {
            return;
        }
        // 根据编号定位要修改的目标对象
        Customer target = customerService.getCustomer(id);
        if (target == null) {
            System.out.println("--------------指定ID[" + id + "]的客户不存在-----------------");
            return;
        }
        System.out.println("<直接回车表示不修改>");
        System.out.print("姓名(" + target.getName() + ") : ");
        String name = KeyboardUtility.readString(10, target.getName());
        target.setName(name);
        System.out.print("年龄(" + target.getAge() + ") : ");
        int age = KeyboardUtility.readInt(target.getAge());
        target.setAge(age);
        System.out.print("工资(" + target.getSalary() + ") : ");
        int salary = KeyboardUtility.readInt((int) target.getSalary());
        target.setSalary(salary);
        System.out.print("电话(" + target.getPhone() + ") : ");
        String phone = KeyboardUtility.readString(15, target.getPhone());
        target.setPhone(phone);

        customerService.modifyCustomer(id, target);

        System.out.println("---------------------修改完成---------------------");
    }

    /**
     * 删除员工
     */
    private void deleteCustomer () {
        System.out.println("---------------------删除客户---------------------");
        System.out.print("请选择待删除客户ID(-1退出) : ");
        // 获取用户输入的ID
        int id = KeyboardUtility.readInt();
        if (id == -1) {
            return;
        }
        System.out.print("确认是否删除(Y/N) : ");
        // 获取用户输入的确认
        char confirm = KeyboardUtility.readConfirmSelection();
        if (confirm == 'Y') {
            boolean flag = customerService.removeCustomer(id);
            if (flag) {
                System.out.println("---------------------删除完成---------------------");
            } else {
                System.out.println("--------------指定ID[" + id + "]的客户不存在-----------------");
            }
        }
    }

    /**
     * 员工列表
     */
    private void listAllCustomers() {
        System.out.println("---------------------------------客户列表--------------------------------------");
        // 真的获取所有员工
        List<Customer> list = customerService.getList();
        if (list == null || list.size() == 0) {
            System.out.println("没有数据, 请添加新数据...");
        } else {
            System.out.println("ID\t姓名\t\t性别\t\t年龄\t\t工资\t\t\t电话");
            for (Customer customer : list) {
                System.out.println(customer);
            }
        }
        System.out.println("-----------------------------------------------------------------------------");
    }

}

KeyboardUtility.java

package com.atguigu.cms.view;

import java.util.Scanner;

public class KeyboardUtility {
	
    private static Scanner scanner = new Scanner(System.in);

    public static void readReturn() {
        System.out.print("按回车键继续...");
        readKeyBoard(100, true);
    }

    public static char readMenuSelection() {
        char c;
        for (; ; ) {
            String str = readKeyBoard(1, false);
            c = str.charAt(0);
            if (c != '1' && c != '2' && 
                c != '3' && c != '4' && c != '5') {
                System.out.print("选择错误,请重新输入:");
            } else break;
        }
        return c;
    }

    public static char readChar() {
        String str = readKeyBoard(1, false);
        return str.charAt(0);
    }

    public static char readChar(char defaultValue) {
        String str = readKeyBoard(1, true);
        return (str.length() == 0) ? defaultValue : str.charAt(0);
    }

    public static int readInt() {
        int n;
        for (; ; ) {
            String str = readKeyBoard(8, false);
            try {
                n = Integer.parseInt(str);
                break;
            } catch (NumberFormatException e) {
                System.out.print("数字输入错误,请重新输入:");
            }
        }
        return n;
    }

    public static int readInt(int defaultValue) {
        int n;
        for (; ; ) {
            String str = readKeyBoard(8, true);
            if (str.equals("")) {
                return defaultValue;
            }

            try {
                n = Integer.parseInt(str);
                break;
            } catch (NumberFormatException e) {
                System.out.print("数字输入错误,请重新输入:");
            }
        }
        return n;
    }

    public static String readString(int limit) {
        return readKeyBoard(limit, false);
    }

    public static String readString(int limit, String defaultValue) {
        String str = readKeyBoard(limit, true);
        return str.equals("")? defaultValue : str;
    }

    public static char readConfirmSelection() {
        char c;
        for (; ; ) {
            String str = readKeyBoard(1, false).toUpperCase();
            c = str.charAt(0);
            if (c == 'Y' || c == 'N') {
                break;
            } else {
                System.out.print("选择错误,请重新输入:");
            }
        }
        return c;
    }

    private static String readKeyBoard(int limit, boolean blankReturn) {
        String line = "";

        while (scanner.hasNextLine()) {
            line = scanner.nextLine();
            if (line.length() == 0) {
                if (blankReturn) return line;
                else continue;
            }

            if (line.length() < 1 || line.length() > limit) {
                System.out.print("输入长度(不大于" + limit + ")错误,请重新输入:");
                continue;
            }
            break;
        }

        return line;
    }
}

2.5 服务实现入口

CustomerService.java

package com.atguigu.cms.service;

import com.atguigu.cms.dao.CustomerDao;
import com.atguigu.cms.javabean.Customer;
import com.atguigu.cms.utils.JdbcUtil;

import java.sql.SQLException;
import java.util.List;

/**
 * 这是一个具有管理功能的功能类. 内部数据不允许外部随意修改, 具有更好的封装性.
 */
public class CustomerService {


    private CustomerDao customerDao = new CustomerDao();

    /**
     * 用途:返回所有客户对象
     * 返回:集合
     */
    public List<Customer> getList() {

        try {

            return customerDao.getList();

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    }


    /**
     * 用途:添加新客户
     * 参数:customer指定要添加的客户对象
     */
    public void addCustomer(Customer customer) {

        try {

            JdbcUtil.getConnection().setAutoCommit(false);

            customerDao.addCustomer(customer);

            JdbcUtil.getConnection().commit();

        } catch (SQLException e) {

            throw new RuntimeException(e);

        }

    }

    /**
     * 用途:返回指定id的客户对象记录
     * 参数: id 就是要获取的客户的id号.
     * 返回:封装了客户信息的Customer对象
     */
    public Customer getCustomer(int id) {

        try {

            return customerDao.getOne(id);

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    }

    /**
     * 修改指定id号的客户对象的信息
     *
     * @param id   客户id
     * @param cust 对象
     * @return 修改成功返回true, false表明指定id的客户未找到
     */
    public boolean modifyCustomer(int id, Customer cust) {

        int rows = 0;

        try {

            JdbcUtil.getConnection().setAutoCommit(false);

            rows = customerDao.updateById(cust);

            JdbcUtil.getConnection().commit();

        } catch (SQLException e) {

            throw new RuntimeException(e);

        }

        // 返回修改成功
        if (rows == 0) {

            return false;

        }

        return true;

    }

    /**
     * 用途:删除指定id号的的客户对象记录
     * 参数: id 要删除的客户的id号
     * 返回:删除成功返回true;false表示没有找到
     */
    public boolean removeCustomer(int id) {

        int rows = 0;

        try {

            JdbcUtil.getConnection().setAutoCommit(false);

            rows = customerDao.removeById(id);

            JdbcUtil.getConnection().commit();

        } catch (SQLException e) {

            throw new RuntimeException(e);

        }

        if (rows == 0) {

            return false;

        }

        return true;

    }

}

2.6 JavaBean对应的Dao实现

CustomerDao.java

package com.atguigu.cms.dao;

import com.atguigu.cms.javabean.Customer;
import com.atguigu.cms.utils.BaseDao;

import java.sql.SQLException;
import java.util.List;

/**
 * @Title: CustomerDao
 * @Package: com.atguigu.cms.dao
 * @Description:
 * @Author: untifa
 * @Date: 2023/3/26 - 13:15
 */
public class CustomerDao extends BaseDao {

    public List<Customer> getList() throws Exception {

        String sql = "SELECT * FROM t_customer;";

        List<Customer> customers = query(Customer.class, sql);

        return customers;

    }

    public Customer getOne(int id) throws Exception {

        String sql = "SELECT * FROM t_customer WHERE id = ? ;";

        List<Customer> customers = query(Customer.class, sql, id);


        return customers.get(0);

    }

    public void addCustomer(Customer customer) throws SQLException {

        String sql = "INSERT INTO t_customer(name,gender,age,salary,phone) values( ?, ?, ?, ?, ?) ; ";

        update(sql, customer.getName(), customer.getGender(), customer.getAge(), customer.getSalary(), customer.getPhone());

    }

    public int updateById(Customer cust) throws SQLException {

        String sql = "UPDATE t_customer SET name = ?, gender = ?, age = ?, salary = ?, phone = ? WHERE id = ? ;";

        int update = update(sql, cust.getName(), cust.getGender(), cust.getAge(), cust.getSalary(), cust.getPhone(), cust.getId());

        return update;

    }

    public int removeById(int id) throws SQLException {

        String sql = "DELETE FROM t_customer WHERE id = ? ;";

        int update = update(sql, id);

        return update;

    }
}

2.7 durid.properties配置文件

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://192.168.101.130:3306/atguigu
username=root
password=root
maxActive=100
initialSize=10
defaultAutoCommit=true

3. 实现客户信息增删改查的功能

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值