JAVA+Mysql实现图书管理系统-附源码

一、数据库设计

CREATE DATABASE LibraryDB;

USE LibraryDB;

CREATE TABLE Users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(255) NOT NULL,
    password VARCHAR(255) NOT NULL,
    is_admin BOOLEAN DEFAULT FALSE
);

CREATE TABLE Categories (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL
);

CREATE TABLE Books (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    author VARCHAR(255) NOT NULL,
    publisher VARCHAR(255),
    year INT,
    category_id INT,
    FOREIGN KEY (category_id) REFERENCES Categories(id)
);

CREATE TABLE BorrowRecords (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT,
    book_id INT,
    borrow_date DATE,
    return_date DATE,
    FOREIGN KEY (user_id) REFERENCES Users(id),
    FOREIGN KEY (book_id) REFERENCES Books(id)
);

二、Java代码

首先,确保你已经下载并添加了MySQL JDBC驱动程序到你的项目中。你可以在MySQL官网下载驱动程序。

1. 数据库连接类

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

public class DatabaseConnection {
    private static final String URL = "jdbc:mysql://localhost:3306/LibraryDB?useUnicode=true&characterEncoding=UTF-8";
    private static final String USER = "root";
    private static final String PASSWORD = "your_password";

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }
}

2. 用户管理类

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

public class UserManager {
    // 注册用户
    public void registerUser(String username, String password, boolean isAdmin) {
        String sql = "INSERT INTO Users (username, password, is_admin) VALUES (?, ?, ?)";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            pstmt.setBoolean(3, isAdmin);
            pstmt.executeUpdate();
            System.out.println("用户注册成功!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 用户登录
    public boolean loginUser(String username, String password) {
        String sql = "SELECT * FROM Users WHERE username = ? AND password = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                System.out.println("登录成功!");
                return true;
            } else {
                System.out.println("用户名或密码错误!");
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 获取所有用户
    public void getAllUsers() {
        String sql = "SELECT * FROM Users";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                int id = rs.getInt("id");
                String username = rs.getString("username");
                boolean isAdmin = rs.getBoolean("is_admin");

                System.out.printf("ID: %d, 用户名: %s, 是否管理员: %s%n", id, username, isAdmin);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

3. 图书管理类

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

public class BookManager {
    // 添加图书
    public void addBook(String title, String author, String publisher, int year, int categoryId) {
        String sql = "INSERT INTO Books (title, author, publisher, year, category_id) VALUES (?, ?, ?, ?, ?)";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, title);
            pstmt.setString(2, author);
            pstmt.setString(3, publisher);
            pstmt.setInt(4, year);
            pstmt.setInt(5, categoryId);
            pstmt.executeUpdate();
            System.out.println("图书添加成功!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 获取所有图书
    public void getAllBooks() {
        String sql = "SELECT * FROM Books";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                int id = rs.getInt("id");
                String title = rs.getString("title");
                String author = rs.getString("author");
                String publisher = rs.getString("publisher");
                int year = rs.getInt("year");

                System.out.printf("ID: %d, 标题: %s, 作者: %s, 出版社: %s, 年份: %d%n", id, title, author, publisher, year);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 模糊搜索图书
    public void searchBooks(String keyword) {
        String sql = "SELECT * FROM Books WHERE title LIKE ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, "%" + keyword + "%");
            ResultSet rs = pstmt.executeQuery();

            while (rs.next()) {
                int id = rs.getInt("id");
                String title = rs.getString("title");
                String author = rs.getString("author");
                String publisher = rs.getString("publisher");
                int year = rs.getInt("year");

                System.out.printf("ID: %d, 标题: %s, 作者: %s, 出版社: %s, 年份: %d%n", id, title, author, publisher, year);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 更新图书信息
    public void updateBook(int id, String title, String author, String publisher, int year) {
        String sql = "UPDATE Books SET title = ?, author = ?, publisher = ?, year = ? WHERE id = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, title);
            pstmt.setString(2, author);
            pstmt.setString(3, publisher);
            pstmt.setInt(4, year);
            pstmt.setInt(5, id);
            pstmt.executeUpdate();
            System.out.println("图书更新成功!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 删除图书
    public void deleteBook(int id) {
        String sql = "DELETE FROM Books WHERE id = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            pstmt.executeUpdate();
            System.out.println("图书删除成功!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

4. 借书和还书管理类

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

public class BorrowManager {
    // 借书
    public void borrowBook(int userId, int bookId) {
        String sql = "INSERT INTO BorrowRecords (user_id, book_id, borrow_date) VALUES (?, ?, ?)";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, userId);
            pstmt.setInt(2, bookId);
            pstmt.setDate(3, new java.sql.Date(System.currentTimeMillis()));
            pstmt.executeUpdate();
            System.out.println("图书借阅成功!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 还书
    public void returnBook(int userId, int bookId) {
        String sql = "UPDATE BorrowRecords SET return_date = ? WHERE user_id = ? AND book_id = ? AND return_date IS NULL";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setDate(1, new java.sql.Date(System.currentTimeMillis()));
            pstmt.setInt(2, userId);
            pstmt.setInt(3, bookId);
            pstmt.executeUpdate();
            System.out.println("图书归还成功!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

5. 类别管理类

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

public class CategoryManager {
    // 添加类别
    public void addCategory(String name) {
        String sql = "INSERT

 INTO Categories (name) VALUES (?)";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, name);
            pstmt.executeUpdate();
            System.out.println("类别添加成功!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 获取所有类别
    public void getAllCategories() {
        String sql = "SELECT * FROM Categories";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");

                System.out.printf("ID: %d, 类别名称: %s%n", id, name);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 更新类别信息
    public void updateCategory(int id, String name) {
        String sql = "UPDATE Categories SET name = ? WHERE id = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, name);
            pstmt.setInt(2, id);
            pstmt.executeUpdate();
            System.out.println("类别更新成功!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 删除类别
    public void deleteCategory(int id) {
        String sql = "DELETE FROM Categories WHERE id = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            pstmt.executeUpdate();
            System.out.println("类别删除成功!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

6. 图形界面

使用Java Swing来创建图形界面。

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LibraryGUI {
    private JFrame frame;
    private UserManager userManager;
    private BookManager bookManager;
    private BorrowManager borrowManager;
    private CategoryManager categoryManager;

    public LibraryGUI() {
        userManager = new UserManager();
        bookManager = new BookManager();
        borrowManager = new BorrowManager();
        categoryManager = new CategoryManager();

        initialize();
    }

    private void initialize() {
        frame = new JFrame("图书管理系统");
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(3, 2));

        // 用户注册
        JButton registerButton = new JButton("用户注册");
        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username = JOptionPane.showInputDialog("请输入用户名:");
                String password = JOptionPane.showInputDialog("请输入密码:");
                userManager.registerUser(username, password, false);
            }
        });
        panel.add(registerButton);

        // 用户登录
        JButton loginButton = new JButton("用户登录");
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username = JOptionPane.showInputDialog("请输入用户名:");
                String password = JOptionPane.showInputDialog("请输入密码:");
                userManager.loginUser(username, password);
            }
        });
        panel.add(loginButton);

        // 添加图书
        JButton addBookButton = new JButton("添加图书");
        addBookButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String title = JOptionPane.showInputDialog("请输入图书标题:");
                String author = JOptionPane.showInputDialog("请输入图书作者:");
                String publisher = JOptionPane.showInputDialog("请输入出版社:");
                int year = Integer.parseInt(JOptionPane.showInputDialog("请输入出版年份:"));
                int categoryId = Integer.parseInt(JOptionPane.showInputDialog("请输入类别ID:"));
                bookManager.addBook(title, author, publisher, year, categoryId);
            }
        });
        panel.add(addBookButton);

        // 借书
        JButton borrowBookButton = new JButton("借书");
        borrowBookButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int userId = Integer.parseInt(JOptionPane.showInputDialog("请输入用户ID:"));
                int bookId = Integer.parseInt(JOptionPane.showInputDialog("请输入图书ID:"));
                borrowManager.borrowBook(userId, bookId);
            }
        });
        panel.add(borrowBookButton);

        // 还书
        JButton returnBookButton = new JButton("还书");
        returnBookButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int userId = Integer.parseInt(JOptionPane.showInputDialog("请输入用户ID:"));
                int bookId = Integer.parseInt(JOptionPane.showInputDialog("请输入图书ID:"));
                borrowManager.returnBook(userId, bookId);
            }
        });
        panel.add(returnBookButton);

        // 搜索图书
        JButton searchBookButton = new JButton("搜索图书");
        searchBookButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String keyword = JOptionPane.showInputDialog("请输入图书标题关键字:");
                bookManager.searchBooks(keyword);
            }
        });
        panel.add(searchBookButton);

        frame.add(panel, BorderLayout.CENTER);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new LibraryGUI();
            }
        });
    }
}

这个Java程序使用Swing库创建了一个简单的图书管理系统GUI,包含用户注册、用户登录、添加图书、借书、还书和搜索图书的功能。每个功能通过弹出对话框让用户输入相关信息并调用相应的管理类方法。请确保在运行程序之前已经配置好数据库,并将数据库连接信息正确配置在DatabaseConnection类中。

© 版权声明
THE END
喜欢就支持一下吧
点赞11赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容