Java Swing + MySQL 图书管理系统

这是一个使用JavaSwing开发的图书管理系统,集成MySQL数据库,包括图书实体类Book、数据访问对象BookDao、数据库连接工具DBUtil,以及添加图书界面BookAddInterFrm的代码示例,实现了基础的数据操作功能。
摘要由CSDN通过智能技术生成

系列文章目录

Java Swing + MySQL 图书管理系统


前言

项目是使用Java swing开发,可实现基础数据维护、图书类型管理和维护、图书信息管理和维护、注销退出、关于作者简介等功能。界面设计比较简介、适合作为Java课设设计以及学习技术使用。

  • 语言:Java
  • 界面:JavaSwing
  • 数据库:MySQL 8.x

一、项目展示

请添加图片描述
在这里插入图片描述
在这里插入图片描述

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

二、部分代码

1.Book

package org.example.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 图书实体
 *
 * @author MaxBrooks 15905898514@163.com
 * since jdk17
 * @version 2022/12/21 11:17
 */

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {

    /**
     * 图书id
     */
    private int id;
    /**
     * 书名
     */
    private String bookName;
    /**
     * 作者
     */
    private String author;
    /**
     * 性别
     */
    private String sex;
    /**
     * 价格
     */
    private Float price;
    /**
     * 图书类别
     */
    private Integer bookTypeId;
    /**
     * 图书类别
     */
    private String bookTypeName;
    /**
     * 描述
     */
    private String bookDesc;

    public Book(String bookName, String author, String sex, Float price, Integer bookTypeId, String bookDesc) {
        super();
        this.bookName = bookName;
        this.author = author;
        this.sex = sex;
        this.price = price;
        this.bookTypeId = bookTypeId;
        this.bookDesc = bookDesc;
    }

    public Book(int id, String bookName, String author, String sex, Float price, Integer bookTypeId, String bookDesc) {
        super();
        this.id = id;
        this.bookName = bookName;
        this.author = author;
        this.sex = sex;
        this.price = price;
        this.bookTypeId = bookTypeId;
        this.bookDesc = bookDesc;
    }

    public Book(String bookName, String author, Integer bookTypeId) {
        super();
        this.bookName = bookName;
        this.author = author;
        this.bookTypeId = bookTypeId;
    }
}


2.BookDao

package org.example.dao;

import org.example.model.Book;
import org.example.utils.StringUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author MaxBrooks 15905898514@163.com
 * since jdk17
 * @version 2022/12/21 11:28
 */
public class BookDao {


    /**
     * 添加图书
     * @param connection    连接数据库
     * @param book  书籍
     * @return  preparedStatement.executeUpdate(),int
     * @throws Exception    how do I know
     */
    public int add(Connection connection, Book book)throws Exception{
        String sql = "INSERT INTO t_book VALUES (null, ?, ?, ?, ?, ?, ?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, book.getBookName());
        preparedStatement.setString(2, book.getAuthor());
        preparedStatement.setString(3, book.getSex());
        preparedStatement.setFloat(4, book.getPrice());
        preparedStatement.setInt(5, book.getBookTypeId());
        preparedStatement.setString(6, book.getBookDesc());
        return preparedStatement.executeUpdate();
    }

    /**
     * 查找书籍
     * @param connection    连接数据库
     * @param book  书籍
     * @return  preparedStatement.executeUpdate(), int
     * @throws Exception    how do I know
     */
    public ResultSet list(Connection connection, Book book)throws Exception{
        StringBuffer stringBuffer = new StringBuffer("SELECT * FROM t_book b,t_bookType bt WHERE b.bookTypeId = bt.id");
        if(StringUtil.isNotEmpty(book.getBookName())){
            stringBuffer.append(" and b.bookName like '%").append(book.getBookName()).append("%'");
        }
        if(StringUtil.isNotEmpty(book.getAuthor())){
            stringBuffer.append(" and b.author like '%").append(book.getAuthor()).append("%'");
        }
        if(book.getBookTypeId() != null && book.getBookTypeId()!=-1){
            stringBuffer.append(" and b.bookTypeId=").append(book.getBookTypeId());
        }
        PreparedStatement preparedStatement = connection.prepareStatement(stringBuffer.toString());
        return preparedStatement.executeQuery();
    }

    /**
     * 删除书籍
     * @param connection    连接数据库
     * @param id 书籍id号
     * @return  preparedStatement.executeUpdate(), int
     * @throws Exception    how do I know
     */
    public int delete(Connection connection,String id)throws Exception{
        String sql="DELETE FROM t_book WHERE id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, id);
        return preparedStatement.executeUpdate();
    }

    /**
     * 更新书籍
     * @param connection    连接数据库
     * @param book  书籍
     * @return  preparedStatement.executeUpdate(),int
     * @throws Exception    how do I know
     */
    public int update(Connection connection,Book book) throws Exception{
        String sql="UPDATE t_book SET bookName = ?, author = ?, sex = ?, price = ?, bookDesc = ?, bookTypeId = ? WHERE id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, book.getBookName());
        preparedStatement.setString(2, book.getAuthor());
        preparedStatement.setString(3, book.getSex());
        preparedStatement.setFloat(4, book.getPrice());
        preparedStatement.setString(5, book.getBookDesc());
        preparedStatement.setInt(6, book.getBookTypeId());
        preparedStatement.setInt(7, book.getId());
        return preparedStatement.executeUpdate();
    }


    /**
     * 判断书籍是否存在
     * @param connection    数据库连接
     * @param bookTypeId    书类号
     * @return  存在与否
     * @throws Exception    异常多了什么都有可能
     */
    public boolean existBookByBookTypeId(Connection connection,String bookTypeId)throws Exception{
        String sql="SELECT * FROM t_book WHERE bookTypeId = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, bookTypeId);
        ResultSet rs = preparedStatement.executeQuery();
        return rs.next();
    }

}


3.DBUtil

package org.example.utils;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * 数据库连接类
 *
 * @author MaxBrooks 15905898514@163.com
 * since jdk17
 * @version 2022/12/18 23:13
 */
public class DBUtil {

    /**
     数据库
     */
    private String url = "jdbc:mysql://localhost:3306/sys";
    /**
     * 用户名
     */
    private String username = "root";
    /**
     * 密码
     */
    private String password = "Shangxiao111";
    /**
     * 驱动名称
     */
    private String jdbcName = "com.mysql.cj.jdbc.Driver";

    /**
     * 获取数据库连接
     * @return  返回连接
     * @throws Exception 没连上
     */
    public Connection getConnection() throws Exception{
        Class.forName(jdbcName);
        Connection connection = DriverManager.getConnection(url, username, password);
        return connection;
    }


    /**
     * 关闭数据库连接
     * @param connection    数据库连接
     * @throws Exception    异常
     */
    public void closeConnection(Connection connection) throws Exception{
        if (connection != null){
            connection.close();
        }
    }
}

4.BookAddInterFrm

package org.example.view.addview;

import org.example.dao.BookDao;
import org.example.dao.BookTypeDao;
import org.example.model.Book;
import org.example.model.BookType;
import org.example.utils.DBUtil;
import org.example.utils.StringUtil;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Objects;
import java.util.logging.Logger;

/**
 * @author MaxBrooks 15905898514@163.com
 * since jdk17
 * @version 2022/12/21 12:03
 */
public class BookAddInterFrm extends JInternalFrame {
    private final JTextField bookNameTxt;
    private final JTextField authorTxt;
    private final ButtonGroup buttonGroup = new ButtonGroup();
    private final JTextField priceTxt;
    private final JComboBox bookTypeJcb;
    private final JTextArea bookDescTxt;
    private final JRadioButton manJrb;
    private final JRadioButton femaleJrb;

    private final DBUtil dbUtil = new DBUtil();
    private final BookTypeDao bookTypeDao = new BookTypeDao();
    private final BookDao bookDao = new BookDao();


    /**
     * Create the frame.
     */
    public BookAddInterFrm() {
        setClosable(true);
        setIconifiable(true);
        setTitle("图书添加");
        setBounds(100, 100, 450, 467);

        JLabel label = new JLabel("图书名称:");

        bookNameTxt = new JTextField();
        bookNameTxt.setColumns(10);

        JLabel label1 = new JLabel("图书作者:");

        authorTxt = new JTextField();
        authorTxt.setColumns(10);

        JLabel label2 = new JLabel("作者性别:");

        manJrb = new JRadioButton("男");
        buttonGroup.add(manJrb);
        manJrb.setSelected(true);

        femaleJrb = new JRadioButton("女");
        buttonGroup.add(femaleJrb);

        JLabel label3 = new JLabel("图书价格:");

        priceTxt = new JTextField();
        priceTxt.setColumns(10);

        JLabel label4 = new JLabel("图书描述:");

        bookDescTxt = new JTextArea();

        JLabel label5 = new JLabel("图书类别:");

        bookTypeJcb = new JComboBox();

        JButton button = new JButton("添加");
        button.addActionListener(this::bookAddActionPerformed);
        button.setIcon(new ImageIcon(Objects.requireNonNull(BookAddInterFrm.class.getResource("/add.png"))));

        JButton button1 = new JButton("重置");
        button1.addActionListener(this::resetValueActionPerformed);
        button1.setIcon(new ImageIcon(Objects.requireNonNull(BookAddInterFrm.class.getResource("/reset.png"))));
        GroupLayout groupLayout = new GroupLayout(getContentPane());
        groupLayout.setHorizontalGroup(
            groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addGap(42)
                    .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addGroup(groupLayout.createSequentialGroup()
                            .addComponent(button)
                            .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(button1)
                            .addGap(232))
                        .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addComponent(label5)
                            .addGroup(groupLayout.createSequentialGroup()
                                .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                                    .addComponent(label4)
                                    .addComponent(label2)
                                    .addComponent(label))
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                                    .addGroup(groupLayout.createSequentialGroup()
                                        .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
                                            .addComponent(bookNameTxt, GroupLayout.PREFERRED_SIZE, 88, GroupLayout.PREFERRED_SIZE)
                                            .addGroup(groupLayout.createSequentialGroup()
                                                .addComponent(manJrb)
                                                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(femaleJrb))
                                            .addComponent(bookTypeJcb, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                        .addGap(35)
                                        .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
                                            .addGroup(groupLayout.createSequentialGroup()
                                                .addComponent(label1)
                                                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(authorTxt, GroupLayout.PREFERRED_SIZE, 91, GroupLayout.PREFERRED_SIZE))
                                            .addGroup(groupLayout.createSequentialGroup()
                                                    .addComponent(label3)
                                                    .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                                                    .addComponent(priceTxt))))
                                    .addComponent(bookDescTxt))
                                .addContainerGap(44, Short.MAX_VALUE)))))
        );
        groupLayout.setVerticalGroup(
            groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addGap(42)
                    .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                        .addComponent(label)
                        .addComponent(bookNameTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addComponent(label1)
                        .addComponent(authorTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                    .addGap(29)
                    .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                        .addComponent(label2)
                        .addComponent(manJrb)
                        .addComponent(femaleJrb)
                        .addComponent(label3)
                        .addComponent(priceTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                    .addGap(33)
                    .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                        .addComponent(label5)
                        .addComponent(bookTypeJcb, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                    .addGap(30)
                    .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addComponent(label4)
                        .addComponent(bookDescTxt, GroupLayout.PREFERRED_SIZE, 137, GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
                    .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                        .addComponent(button)
                        .addComponent(button1))
                    .addGap(42))
        );
        getContentPane().setLayout(groupLayout);

        /*
         * 设置文本域边框
         */
        bookDescTxt.setBorder(new LineBorder(new java.awt.Color(127,157,185), 1, false));
        fillBookType();
    }


    /**
     * 重置事件处理
     * @param e event
     */
    private void resetValueActionPerformed(ActionEvent e) {
        this.resetValue();
    }


    /**
     * 图书添加事件处理
     * @param event event
     */
    private void bookAddActionPerformed(ActionEvent event) {
        String bookName = this.bookNameTxt.getText();
        String author = this.authorTxt.getText();
        String price = this.priceTxt.getText();
        String bookDesc = this.bookDescTxt.getText();

        if(StringUtil.isEmpty(bookName)){
            JOptionPane.showMessageDialog(null, "图书名称不能为空");
            return;
        }

        if(StringUtil.isEmpty(author)){
            JOptionPane.showMessageDialog(null, "图书作者不能为空");
            return;
        }

        if(StringUtil.isEmpty(price)){
            JOptionPane.showMessageDialog(null, "图书价格不能为空");
            return;
        }

        String sex = "";
        if(manJrb.isSelected()){
            sex = "男";
        }else if(femaleJrb.isSelected()){
            sex = "女";
        }

        BookType bookType = (BookType) bookTypeJcb.getSelectedItem();
        int bookTypeId = bookType.getId();

        Book book = new Book(bookName,author, sex, Float.parseFloat(price) , bookTypeId,  bookDesc);

        Connection con = null;
        try{
            con = dbUtil.getConnection();
            int addNum = bookDao.add(con, book);
            if(addNum == 1){
                JOptionPane.showMessageDialog(null, "图书添加成功");
                resetValue();
            }else{
                JOptionPane.showMessageDialog(null, "图书添加失败");
            }
        }catch(Exception e){
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "图书添加失败");
        }finally{
            try {
                dbUtil.closeConnection(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }




    /**
     * 重置表单
     */
    private void resetValue(){
        this.bookNameTxt.setText("");
        this.authorTxt.setText("");
        this.priceTxt.setText("");
        this.manJrb.setSelected(true);
        this.bookDescTxt.setText("");
        if(this.bookTypeJcb.getItemCount()>0){
            this.bookTypeJcb.setSelectedIndex(0);
        }
    }


    /**
     * 初始化图书类别下拉框
     */
    private void fillBookType(){
        Connection con = null;
        BookType bookType = null;
        try{
            con = dbUtil.getConnection();
            ResultSet rs = bookTypeDao.list(con, new BookType());
            while(rs.next()){
                bookType = new BookType();
                bookType.setId(rs.getInt("id"));
                bookType.setBookTypeName(rs.getString("bookTypeName"));
                this.bookTypeJcb.addItem(bookType);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            Logger.getGlobal().info("finished!");
        }
    }
}


5.MainFrame

package org.example.view;

import org.example.view.addview.BookAddInterFrm;
import org.example.view.addview.BookTypeAddInterFrm;
import org.example.view.manageview.BookManageInterFrm;
import org.example.view.manageview.BookTypeManageInterFrm;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.util.Objects;

/**
 * 主窗体
 *
 * @author MaxBrooks 15905898514@163.com
 * since jdk17
 * @version 2022/12/21 9:55
 */

public class MainFrame extends JFrame {

    private JPanel contentPane;
    private JDesktopPane table =null;


    /**
     * Create the frame.
     */
    public MainFrame() {
        // 图书管理系统主界面
        setTitle("图书管理系统主界面");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);

        // 老师要求加的01
        this.setExtendedState(Frame.MAXIMIZED_BOTH);
        init();

        // 设置JFrame最大化
        this.setExtendedState(Frame.MAXIMIZED_BOTH);
    }

    public void init(){
        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        // 1.基本数据维护
        JMenu mnNewMenu = new JMenu("基本数据维护");
        mnNewMenu.setIcon(new ImageIcon(Objects.requireNonNull(getClass().getResource("/base.png"))));
        menuBar.add(mnNewMenu);

        // 1.1.图书类别管理
        JMenu mnNewMenu1 = new JMenu("图书类别管理");
        mnNewMenu1.setIcon(new ImageIcon(Objects.requireNonNull(getClass().getResource("/bookTypeManager.png"))));
        mnNewMenu.add(mnNewMenu1);

        // 1.1.1.图书类别添加
        JMenuItem menuItem = new JMenuItem("图书类别添加");
        menuItem.addActionListener(e -> {
            BookTypeAddInterFrm bookTypeAddInterFrm = new BookTypeAddInterFrm();
            bookTypeAddInterFrm.setVisible(true);
            table.add(bookTypeAddInterFrm);
        });
        menuItem.setIcon(new ImageIcon(Objects.requireNonNull(getClass().getResource("/add.png"))));
        mnNewMenu1.add(menuItem);

        // 1.1.2.图书类别维护
        JMenuItem menuItem1 = new JMenuItem("图书类别维护");
        menuItem1.addActionListener(e -> {
            BookTypeManageInterFrm bookTypeManageInterFrm=new BookTypeManageInterFrm();
            bookTypeManageInterFrm.setVisible(true);
            table.add(bookTypeManageInterFrm);
        });
        menuItem1.setIcon(new ImageIcon(Objects.requireNonNull(getClass().getResource("/edit.png"))));
        mnNewMenu1.add(menuItem1);

        // 1.2.图书管理
        JMenu mnNewMenu2 = new JMenu("图书管理");
        mnNewMenu2.setIcon(new ImageIcon(Objects.requireNonNull(getClass().getResource("/bookManager.png"))));
        mnNewMenu.add(mnNewMenu2);

        // 1.2.1.图书添加
        JMenuItem menuItem2 = new JMenuItem("图书添加");
        menuItem2.addActionListener(arg0 -> {
            BookAddInterFrm bookAddInterFrm=new BookAddInterFrm();
            bookAddInterFrm.setVisible(true);
            table.add(bookAddInterFrm);
        });
        menuItem2.setIcon(new ImageIcon(Objects.requireNonNull(getClass().getResource("/add.png"))));
        mnNewMenu2.add(menuItem2);

        // 1.2.2.图书维护
        JMenuItem menuItem3 = new JMenuItem("图书维护");
        menuItem3.addActionListener(arg0 -> {
            BookManageInterFrm bookManageInterFrm=new BookManageInterFrm();
            bookManageInterFrm.setVisible(true);
            table.add(bookManageInterFrm);
        });
        menuItem3.setIcon(new ImageIcon(Objects.requireNonNull(getClass().getResource("/edit.png"))));
        mnNewMenu2.add(menuItem3);

        // 1.3.安全退出
        JMenuItem menuItemExit = new JMenuItem("安全退出");
        menuItemExit.addActionListener(e -> {
            int result=JOptionPane.showConfirmDialog(null, "是否退出系统");
            if(result==0){
                dispose();
                setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            }
        });
        menuItemExit.setIcon(new ImageIcon(Objects.requireNonNull(getClass().getResource("/exit.png"))));
        mnNewMenu.add(menuItemExit);

        // 2.关于我们
        JMenu menu = new JMenu("关于我们");
        menu.setIcon(new ImageIcon(Objects.requireNonNull(getClass().getResource("/about.png"))));
        menuBar.add(menu);

        // 2.1关于Java
        JMenuItem jMenuItem = new JMenuItem("关于Java");
        jMenuItem.addActionListener(arg0 -> {
            JavaInternalFrame java1234InterFrm=new JavaInternalFrame();
            java1234InterFrm.setVisible(true);
            table.add(java1234InterFrm);
        });
        jMenuItem.setIcon(new ImageIcon(Objects.requireNonNull(getClass().getResource("/about.png"))));
        menu.add(jMenuItem);


        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new BorderLayout(0, 0));

        table = new JDesktopPane();
        contentPane.add(table, BorderLayout.CENTER);

    }
}

配置

1、idea直接导入解压文件夹,等待pom中的依赖完成加载
2、打开navicat等数据库可视化软件,运行sql文件夹下的数据库文件
3、修改DBUtil.java中的第24、20、28行的用户名、连接、密码(如果有必要的话)
4、运行Main

如有购买需求,请移步到 面包多 进行购买,CSDN的收费太黑了

面包多中提供了几种不同的版本代码:

  • 有数据库版,提供MySQL支持,数据能够实现增删改查
  • 无数据库版,仅提供界面和部分鼠标点击事件,数据内容无法被修改
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PlutoCtx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值