使用JDBC+javafx写一个简单功能齐全的图书管理系统

目录

1、JDBC的使用

 2、对应包和Java文件的层级关系及对应的含义

3、数据库

4、相关代码

1)、bookmanager包

Ⅰ、main函数

Ⅱ、utils包

Ⅲ、bean包 

Ⅳ、controller包 

 2)resources(为资源文件包,可以看链接文章了解)

Ⅰ、book包

Ⅱ、 login包

5、效果展示(对应功能实现在相应代码中)

1)、登录功能

 2)、注册功能

 3)、后台主页面

 4)、编辑页和添加页

 5)、修改密码页

 6)、注销页

在文章结尾有图书管理系统的效果展示

资源已上传到csdn可以自行下载

1、JDBC的使用

后面会用到大量jdbc语句来实现数据库的增删改查,可以先简单看看下面这篇文章。

JDBC的简单使用与封装_jdbc封装_热爱编程的林兮的博客-CSDN博客

 2、对应包和Java文件的层级关系及对应的含义

 上面DBUtils为jdbc的封装,详情可以看jdbc的简单使用与封装,还有dp.properties文件也在这篇文章中收到,我后面就不再过多概述。

3、数据库

admin:

book:

 category:

4、相关代码

1)、bookmanager包

Ⅰ、main函数

BookManagerApplication

package com.hk.sky.bookmanager;

import com.hk.sky.bookmanager.bean.Admin;
import com.hk.sky.bookmanager.controller.LoginController;
import com.hk.sky.bookmanager.dao.AdminDao;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;


public class BookManagerApplication extends Application {
    AdminDao adminDao=new AdminDao();
    //获取上一次用户登录的信息
    Admin admin=adminDao.getLast();
    @Override
    public void start(Stage stage) throws IOException {
        //登录页面的资源文件为login/login.fxml
        FXMLLoader fxmlLoader = new FXMLLoader(BookManagerApplication.class.getResource("login/login.fxml"));
        //设置登录窗口的长和宽
        Scene scene = new Scene(fxmlLoader.load(), 290, 240);
        stage.setTitle("管理员登录");
        stage.setScene(scene);
        LoginController loginController=fxmlLoader.getController();
        //如果admin不是为null,则说明上一次有用户登录,则直接在登录页面显示账号和密码
        if (admin!=null)
            loginController.set(admin.getAccount(),admin.getPassword());
        stage.show();
    }
    //启动
    public static void main(String[] args) {
        launch();
    }
}

Ⅱ、utils包

DBUtils

package com.hk.sky.bookmanager.utils;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * 封装数据连接,关闭的工具类
 */
public class DBUtils {

    private static String url;
    private static String username;
    private static String password;

    // 读取配置文件
    static {
        Properties prop = new Properties();

        try {
            // DBUtils.class.getClassLoader().getResourceAsStream()方法可以从类路径中读取资源文件
            prop.load(DBUtils.class.getClassLoader().getResourceAsStream("db.properties"));

            // 通过key获取value
            url = prop.getProperty("jdbc.url");
            username = prop.getProperty("jdbc.username");
            password = prop.getProperty("jdbc.password");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    // 将创建连接的方法封装成静态方法,方便调用
    // 如何将url、username、password放到配置文件当中,然后读取出来
    public static Connection getConnection() {
        // 创建连接的时候,有会异常:SQLException,不建议抛出,建立捕获
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(
                    url,
                    username,
                    password
            );
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return conn;
    }
    
    // 将关闭连接的方法封装成静态方法,方便调用
    public static void close(ResultSet rs, PreparedStatement pStmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pStmt != null) {
            try {
                pStmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Ⅲ、bean包 

Admin

package com.hk.sky.bookmanager.bean;

public class Admin {
    //账号
    private String account;
    //密码
    private String password;
    //上一次登录
    private int last;

    public String getAccount() {
        return account;
    }

    public String getPassword() {
        return password;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getLast() {
        return last;
    }

    public void setLast(int last) {
        this.last = last;
    }

    @Override
    public String toString() {
        return "Admin{" +
                "account='" + account + '\'' +
                ", password='" + password + '\'' +
                ", last=" + last +
                '}';
    }
}

book

package com.hk.sky.bookmanager.bean;

public class Book {
    private int id;
    private String bookName;
    private String author;
    private int price;
    private int stock;
    private String publisher;
    private String detail;
    private int typeId;

    public void setDetail(String detail) {
        this.detail = detail;
    }
    public String getDetail() {
        return detail;
    }

    public int getId() {
        return id;
    }

    public String getBookName() {
        return bookName;
    }

    public String getAuthor() {
        return author;
    }

    public int getPrice() {
        return price;
    }

    public int getStock() {
        return stock;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public void setStock(int stock) {
        this.stock = stock;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    public void setTypeId(int typeId) {
        this.typeId = typeId;
    }

    public int getTypeId() {
        return typeId;
    }
    public Book(){}
    public Book(String name, String author, String publisher, int price, String detail, int stock, int typeId) {
        this.bookName = name;
        this.author = author;
        this.publisher = publisher;
        this.price = price;
        this.detail = detail;
        this.stock = stock;
        this.typeId = typeId;
    }
}

Category

package com.hk.sky.bookmanager.bean;

public class Category {
    private int id;
    private String typeName;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTypeName() {
        return typeName;
    }

    public void setTypeName(String typeName) {
        this.typeName = typeName;
    }

    @Override
    public String toString() {
        return typeName;
    }
}

Ⅳ、controller包 

AddController

package com.hk.sky.bookmanager.controller;

import com.hk.sky.bookmanager.bean.Book;
import com.hk.sky.bookmanager.bean.Category;
import com.hk.sky.bookmanager.dao.BookDao;
import com.hk.sky.bookmanager.dao.CategoryDao;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.stage.Stage;

import java.net.URL;
import java.sql.SQLException;
import java.util.*;


public class AddController implements Initializable {
    @FXML
    public Button add;
    @FXML
    public Button edit;

    @FXML
    private ComboBox<Category> categoryComboBox;

    private ObservableList<Category> observableList = FXCollections.observableArrayList();

    private CategoryDao categoryDao = new CategoryDao();

    private BookDao bookDao = new BookDao();

    @FXML
    private TextField bookName;
    @FXML
    private TextField bookAuthor;
    @FXML
    private TextField bookPublisher;
    @FXML
    private TextField bookPrice;
    @FXML
    private TextField detail;
    @FXML
    private TextField bookStock;
    public Book book;

    public void setBook(Book book) {
        this.book = book;
    }
    //B用来判断是添加书籍还是编辑书籍
    public boolean B;
    public void setB(boolean i){
        this.B=i;
    }
    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        Platform.runLater(() -> {
            // 页面第一次加载的时候,就显示下拉列表
            observableList.clear();
            List<Category> categories = categoryDao.getAllCategories();
            observableList.addAll(categories);
            categoryComboBox.setItems(observableList);
            //添加书籍  修改书籍
            if (B){
                add.setVisible(true);
                add.setText("添加");
                edit.setVisible(false);
                edit.setText("");
                categoryComboBox.setValue(categories.get(0));
            }else {
                bookName.setText(book.getBookName());
                bookAuthor.setText(book.getAuthor());
                bookPublisher.setText(book.getPublisher());
                bookPrice.setText(String.valueOf(book.getPrice()));
                detail.setText(book.getDetail());
                bookStock.setText(String.valueOf(book.getStock()));
                categoryComboBox.setValue(categories.get(book.getTypeId()));
                edit.setVisible(true);
                edit.setText("修改");
                add.setDisable(false);
                add.setText("");
            }
        });
    }
    //给添加按钮设置点击事件
    public void addBook() throws SQLException {
        // 用户点击添加按钮时,获取所有的数据,并插入到数据库当中
        String name = bookName.getText();
        String author = bookAuthor.getText();
        String publisher = bookPublisher.getText();
        String detail1 = detail.getText();

        // 将格式进行转换
        // 表单验证,判断用户是否输入内容
        if (name.equals("") || author.equals("") || publisher.equals("") || detail1.equals("") ||
                bookPrice.getText().equals("") || bookStock.getText().equals("")) {

            Alert error = new Alert(Alert.AlertType.ERROR, "输入错误");
            Button err = new Button();
            error.setTitle("您的书籍信息输入错误!");
            error.setHeaderText("请正确填写所要添加书籍的信息!");
            err.setOnAction((ActionEvent e) -> {
                error.showAndWait();
            });
            Optional<ButtonType> result = error.showAndWait();
        } else if (!bookPrice.getText().matches("[1-9]+[0-9]*")||!bookStock.getText().matches("[1-9]+[0-9]*")){
            Alert error = new Alert(Alert.AlertType.ERROR, "输入错误");
            Button err = new Button();
            error.setTitle("您的书籍信息输入错误!");
            error.setHeaderText("库存和价格必须为整数!");
            err.setOnAction((ActionEvent e) -> {
                error.showAndWait();
            });
            Optional<ButtonType> result = error.showAndWait();
        }else{
            // 思路:将上面获取到的数据封装成book,然后插入到数据库当中
            // 但是仔细思考,我们会碰到一个难点:如何获取ComboBox的选项?也就是说如何知道用户选的是哪一个类型的书籍?
            Category selectedCategory = categoryComboBox.getValue();
            int price = Integer.parseInt(bookPrice.getText());
            int stock = Integer.parseInt(bookStock.getText());

            // 将所有的数据封装成书籍
            Book book = new Book(name, author, publisher, price, detail1, stock, selectedCategory.getId());
            // 调用BookDao中的方法将数据插入到数据库当中
            Alert information = new Alert(Alert.AlertType.INFORMATION, "恭喜您书籍添加成功");
            Button err = new Button();
            information.setTitle("添加成功!");
            information.setHeaderText("林氏图书馆又收录了一本新书,感谢!");
            err.setOnAction((ActionEvent e) -> {
                information.showAndWait();
            });
            Optional<ButtonType> result = information.showAndWait();

            // 插入成功之后,首先当前属性应该关闭
            if (bookDao.insertBook(book)){
                ((Stage) bookName.getScene().getWindow()).close();
            }
        }
    }
    //给编辑按钮设置点击事件
    public void editBook(ActionEvent actionEvent) throws SQLException{
        // 用户点击添加按钮时 ,获取所有的数据,并插入到数据库当中
        String name = bookName.getText();
        String author = bookAuthor.getText();
        String publisher = bookPublisher.getText();
        String detail1 = detail.getText();

        // 将格式进行转换
        // 表单验证,判断用户是否输入内容
        if (name.equals("")||author.equals("")||publisher.equals("")||detail1.equals("")||
                bookPrice.getText().equals("")||bookStock.getText().equals("")){

            Alert error=new Alert(Alert.AlertType.ERROR,"输入错误");
            Button err=new Button();
            error
  • 63
    点赞
  • 85
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 59
    评论
评论 59
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

热爱编程的林兮

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

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

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

打赏作者

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

抵扣说明:

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

余额充值