1.系统功能
本系统是控制台版java图书管理系统,实现了用户的注册登录,管理员的登录,用户可以购买图书和查看图书购买记录,管理员可以对用户信息进行增删查改、可以查看图书信息、上架新的图书、修改图书库存以及删除图书。
如遇到bug,请在评论区留言或私信我~
2.系统简要演示
3.数据库表的创建
新建数据库lib_dtb,然后在桌面建立lib_dtb.sql文件,写入以下sq语句,然后点击lib_dtb数据库中的表右键运行该sql文件,数据库表即导入成功,数据库成功创建。
/*
Navicat Premium Data Transfer
Source Server : MySql
Source Server Type : MySQL
Source Server Version : 80036
Source Host : localhost:3306
Source Schema : lib_dtb
Target Server Type : MySQL
Target Server Version : 80036
File Encoding : 65001
Date: 30/06/2024 23:03:35
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for admin
-- ----------------------------
DROP TABLE IF EXISTS `admin`;
CREATE TABLE `admin` (
`id` int UNSIGNED NOT NULL AUTO_INCREMENT,
`username` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`password` varchar(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `username`(`username` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '管理员' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of admin
-- ----------------------------
INSERT INTO `admin` VALUES (1, 'admin', 'admin');
-- ----------------------------
-- Table structure for buy_table
-- ----------------------------
DROP TABLE IF EXISTS `buy_table`;
CREATE TABLE `buy_table` (
`name` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '用户姓名',
`library` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '图书名字',
`buy_time` datetime NOT NULL COMMENT '购买时间'
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '用户购买图书记录表' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of buy_table
-- ----------------------------
-- ----------------------------
-- Table structure for library
-- ----------------------------
DROP TABLE IF EXISTS `library`;
CREATE TABLE `library` (
`id` int UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键id',
`name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '图书名字',
`author` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '作者',
`price` decimal(5, 2) NOT NULL COMMENT '图书价格,可以保留两位小数,总共5位',
`count` int UNSIGNED NOT NULL COMMENT '图书数量',
`Shelf_time` datetime NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '图书表' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of library
-- ----------------------------
INSERT INTO `library` VALUES (1, '平凡世界', '路遥', 46.00, 10, '2024-04-15 22:02:59');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键id',
`username` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '用户名,唯一',
`password` varchar(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '密码',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `username`(`username` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 17 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '用户表' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (16, 'lisi', '123');
SET FOREIGN_KEY_CHECKS = 1;
4.建立数据库连接
导入jar包,首先建立一个lib文件夹,然后将jar包复制粘贴进去,在右键选择add as library
5.系统包结构如下
6.代码实现
AdminLoginSuccess.java
package com.java.main.common;
import java.util.Scanner;
/**
* 管理员登录成功
*/
public class AdminLoginSuccess {
public AdminLoginSuccess() {
Scanner sc = new Scanner(System.in);
System.out.println("******************请选择***********************");
System.out.println("******************1-用户管理***********************");
System.out.println("******************2-图书管理***********************");
System.out.print("请输入:");
int num = sc.nextInt();
try {
switch (num) {
case 1:
new UserAdmin();
break;
case 2:
new LibraryAdmin();
default:
System.out.println("没有这个选择");
new AdminLoginSuccess();
break;
}
} catch (Exception e) {
System.out.println("请输入数字");
new AdminLoginSuccess();
}
}
}
LibraryAdmin.java
package com.java.main.common;
import com.java.main.pojo.Library;
import com.java.main.utils.Connect;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
/**
* 图书管理
*/
public class LibraryAdmin {
public LibraryAdmin() throws SQLException, ClassNotFoundException {
//获取图书库存为0的书籍
ResultSet rs1 = Connect.queryAll("select * from library where count='0'");
while (rs1.next()) {
System.out.println("========================图书" + rs1.getString("name") + "的库存为0了,请增加库存!!!" +
"========================");
}
Scanner sc = new Scanner(System.in);
//图书集合
ArrayList<Library> list = new ArrayList<>();
ResultSet rs2 = Connect.queryAll("select * from library");
while (rs2.next()) {
Integer id = rs2.getInt("id");
String libraryName = rs2.getString("name");
String authorName = rs2.getString("author");
Double price = rs2.getDouble("price");
Integer count = rs2.getInt("count");
//获取上架时间
Timestamp shelf_time = rs2.getTimestamp("Shelf_time");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(shelf_time);
list.add(new Library(id, libraryName, authorName, price, count, time));
}
System.out.println("请输入你的选择:1查看所有图书信息 2增加图书 3修改图书库存 4删除图书 5选择用户/图书管理");
String numStr = sc.nextLine();
try {
switch (Integer.parseInt(numStr)) {
case 1:
LookForInfo(list);
break;
case 2:
InsertBook(list);
break;
case 3:
EditBook(list);
break;
case 4:
deleteBook(list);
break;
case 5:
new AdminLoginSuccess();
break;
default:
System.out.println("没有这个选项~");
break;
}
} catch (Exception e) {
System.out.println("请输入数字!不能输入其它字符~");
}
rs2.close();
rs1.close();
}
/**
* 修改图书库存
*
* @param list
* @throws SQLException
* @throws ClassNotFoundException
*/
private void EditBook(ArrayList<Library> list) throws SQLException, ClassNotFoundException {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入要增加图书库存的图书名字:");
String name = sc.nextLine();
int index = getResult(list, name);
if (index >= 0) {
//存在
System.out.println("请输入增加的库存数量:");
Integer count1 = sc.nextInt();
Integer count2 = list.get(index).getCount();
Integer count = count1 + count2;
String sql = "update library set count='" + count + "' where name='" + name + "'";
Connect.edit(sql);
System.out.println("库存添加成功!");
new LibraryAdmin();
break;
} else {
System.out.println("不存在该图书!请重新输入~");
}
}
}
/**
* 增加图书
*
* @param list
* @throws SQLException
* @throws ClassNotFoundException
*/
private void InsertBook(ArrayList<Library> list) throws SQLException, ClassNotFoundException {
Scanner sc = new Scanner(System.in);
System.out.println("请输入要增加的图书名:");
String name = sc.next();
System.out.println("请输入作者名:");
String author = sc.next();
System.out.println("请输入价格:");
Double price = sc.nextDouble();
System.out.println("请输入图书数量:");
Integer count = sc.nextInt();
//获取上架时间
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(d);
String sql = " insert into library(name, author, price, count, Shelf_time) values('" + name + "','" + author + "','" +
price + "','" + count + "','" + time + "')";
Connect.edit(sql);
System.out.println("添加成功!");
new LibraryAdmin();
}
/**
* 查询所有图书信息
*
* @param list
* @throws SQLException
* @throws ClassNotFoundException
*/
private void LookForInfo(ArrayList<Library> list) throws SQLException, ClassNotFoundException {
System.out.println("图书信息如下:");
for (Library library : list) {
System.out.println("图书编号:" + library.getId() + " 图书名字:《" + library.getName() + " 》 图书作者:" + library.getAuthor()
+ " 图书价格:" + library.getPrice() + " 图书库存" + library.getCount() + " 图书上架时间:" + library.getTime());
}
new LibraryAdmin();
}
/**
* 根据图书名删除图书
*
* @param list
*/
public void deleteBook(ArrayList<Library> list) throws SQLException, ClassNotFoundException {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入要删除的图书名字");
String name = sc.next();
Integer index = getResult(list, name);
if (index >= 0) {
//存在
try {
Connect.edit("delete from library where name='" + name + "'");
System.out.println("删除成功");
new LibraryAdmin();
break;
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
//不存在
System.out.println("要删除的图书名字不存在,请重新输入");
System.out.println("是否继续根据图书名删除图书操作?输入yes/no");
String continue1 = "yes";
String exit = "no";
String choose = sc.next();
if (choose.equals(continue1)) {
//继续执行
deleteBook(list);
} else if (choose.equals(exit)) {
new LibraryAdmin();
}
}
}
}
/**
* 根据图书名判断图书是否存在
*
* @param list
* @param name
* @return
*/
public Integer getResult(ArrayList<Library> list, String name) {
for (int i = 0; i < list.size(); i++) {
if (name.equals(list.get(i).getName())) {
//存在
return i;
}
}
return -1;
}
}
UserAdmin.java
package com.java.main.common;
import com.java.main.pojo.User;
import com.java.main.utils.Connect;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.function.Consumer;
/**
* 用户管理
*/
public class UserAdmin {
public UserAdmin() throws SQLException, ClassNotFoundException {
Scanner sc = new Scanner(System.in);
//用户信息
ArrayList<User> list = new ArrayList<>();
String sql = "select * from user";
//连接数据库
ResultSet rs = Connect.queryAll(sql);
while (rs.next()) {
list.add(new User(rs.getInt("id"), rs.getString("username"), rs.getString("password")));
}
rs.close();
System.out.println("请输入你的选择:1查看所有用户信息 2删除用户信息 3修改用户信息 4增加用户信息 5选择用户/图书管理");
String numStr = sc.nextLine();
try {
int num = Integer.parseInt(numStr);
switch (num) {
case 1:
LookUser(list);
break;
case 2:
Delete(list);
break;
case 3:
UpdateUser(list);
break;
case 4:
InsertUser(list);
break;
case 5:
new AdminLoginSuccess();
break;
default:
System.out.println("没有这个选项!");
new UserAdmin();
break;
}
} catch (Exception e) {
System.out.println("请输入数字!");
new UserAdmin();
}
}
/**
* 修改用户信息
*
* @param list
* @throws SQLException
* @throws ClassNotFoundException
*/
private void UpdateUser(ArrayList<User> list) throws SQLException, ClassNotFoundException {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入要修改的用户id:");
int id = sc.nextInt();
boolean flag = getResult(list, id);
if (flag) {
//输入的id存在
System.out.println("请输入修改后的用户名:");
String username = sc.next();
boolean result1 = flag(username);
if (result1) {
//符合要求
System.out.println("请修改后的密码:");
String pwd = sc.next();
boolean result2 = pwdFlag(pwd);
if (result2) {
//符合要求
String sql = "update user set username='" + username + "',password='" + pwd + "' where id=" + id;
Connect.edit(sql);
System.out.println("用户信息修改成功!");
new UserAdmin();
break;
} else {
//不符合要求
System.out.println("密码只能由数字和字母组成,最少6位,最多15位");
}
} else {
//不符合要求
System.out.println("用户名要求4-10位且全为字母,请重新输入吧");
}
} else {
System.out.println("输入的用户id在数据库中不存在,请重新输入~");
System.out.println("是否继续执行修改用户信息操作?输入yes/no");
String continue1 = "yes";
String exit = "no";
String choose = sc.next();
if (choose.equals(continue1)) {
//继续执行
UpdateUser(list);
} else if (choose.equals(exit)) {
new UserAdmin();
}
}
}
}
/**
* 增加用户信息
*
* @param list
* @throws SQLException
* @throws ClassNotFoundException
*/
private void InsertUser(ArrayList<User> list) throws SQLException, ClassNotFoundException {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入用户名:");
String username = sc.nextLine();
//判断用户名是否符合要求
boolean flag1 = flag(username);
if (flag1) {
//符合要求
boolean flag = getUserFlag(list, username);
if (!flag) {
//输入的用户名在数据库不存在,执行增加操作
System.out.println("请输入密码:");
String pwd = sc.nextLine();
String sql = "insert into user(username,password) values('" + username + "','" + pwd + "')";
Connect.edit(sql);
System.out.println("添加成功!");
new UserAdmin();
break;
} else {
System.out.println("输入的用户名在数据库中已经存在,请重新输入!");
System.out.println("是否继续执行增加用户信息操作?输入yes/no");
String continue1 = "yes";
String exit = "no";
String choose = sc.next();
if (choose.equals(continue1)) {
//继续执行
InsertUser(list);
} else if (choose.equals(exit)) {
new UserAdmin();
}
}
} else {
//不符合要求
System.out.println("用户名要求4-10位且全为字母,请重新输入吧");
}
}
}
/**
* 删除用户信息
*
* @param list
* @throws SQLException
* @throws ClassNotFoundException
*/
private void Delete(ArrayList<User> list) throws SQLException, ClassNotFoundException {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入你要删除的用户id");
int id = sc.nextInt();
boolean flag = getResult(list, id);
if (flag) {
//id存在
String sql = "delete from user where id=" + id;
Connect.edit(sql);
System.out.println("删除成功!");
new UserAdmin();
break;
} else {
//id不存在
System.out.println("输入的用户id不存在,请重新输入");
System.out.println("是否继续执行删除用户信息操作?输入yes/no");
String continue1 = "yes";
String exit = "no";
String choose = sc.next();
if (choose.equals(continue1)) {
//继续执行
Delete(list);
} else if (choose.equals(exit)) {
new UserAdmin();
}
}
}
}
/**
* 查看所有用户信息
*
* @param list
* @throws SQLException
* @throws ClassNotFoundException
*/
private void LookUser(ArrayList<User> list) throws SQLException, ClassNotFoundException {
//遍历用户集合
System.out.println("用户信息如下");
list.forEach(new Consumer<User>() {
@Override
public void accept(User user) {
System.out.println(user.getId() + " " + user.getUsername() + " " + user.getPassword());
}
});
new UserAdmin();
}
/**
* 在删除用户信息的时候,判断用户输入的id是否存在
*
* @param list
* @param id
* @return
*/
public boolean getResult(ArrayList<User> list, int id) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getId() == id) {
//存在
return true;
}
}
//不存在
return false;
}
/**
* 查询输入的用户名是否存在
*
* @param list
* @param username
* @return
*/
private boolean getUserFlag(ArrayList<User> list, String username) {
for (int i = 0; i < list.size(); i++) {
if (username.equals(list.get(i).getUsername())) {
//用户名存在
return true;
}
}
//不存在
return false;
}
/**
* 最少4位,最多10位
*
* @param username 用户名
* @return 布尔值
*/
public boolean flag(String username) {
//只能为字母,最少4位,最多10位
String regex = "[a-zA-Z]{4,10}";
return username.matches(regex);
}
/**
* 最少6位,最多15位
*
* @param password 密码
* @return 布尔值
*/
public boolean pwdFlag(String password) {
//只能为数字和字母,最少6位,最多15位
String regex = "[a-zA-Z0-9]{6,15}";
return password.matches(regex);
}
}
UserBuyLibrary.java
package com.java.main.common;
import com.java.main.pojo.UserBuy;
import com.java.main.pojo.Library;
import com.java.main.utils.Connect;
import javax.swing.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
import java.util.function.Consumer;
/**
* 用户进行图书购买
*/
public class UserBuyLibrary {
private static String name;
public UserBuyLibrary(String name) {
this.name = name;
System.out.println("欢迎来到图书商城");
System.out.println("当前的登录用户:" + name);
}
public static void main() throws SQLException, ClassNotFoundException {
//创建图书集合
ArrayList<Library> list = new ArrayList<>();
//用户购买记录
ArrayList<UserBuy> buyList = new ArrayList<>();
//连接数据库 将图书信息添加到集合中
ResultSet rs1 = Connect.queryAll("select * from library");
while (rs1.next()) {
Integer id = rs1.getInt("id");
String libraryName = rs1.getString("name");
String authorName = rs1.getString("author");
Double price = rs1.getDouble("price");
Integer count = rs1.getInt("count");
//获取上架时间
Timestamp shelf_time = rs1.getTimestamp("Shelf_time");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(shelf_time);
list.add(new Library(id, libraryName, authorName, price, count, time));
}
rs1.close();
//获取用户购买记录
String sql = "select * from buy_table";
ResultSet rs2 = Connect.queryAll(sql);
while (rs2.next()) {
Timestamp buyTime = rs2.getTimestamp("buy_time");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(buyTime);
buyList.add(new UserBuy(rs2.getString("name"), rs2.getString("library"), time));
}
rs2.close();
Scanner sc = new Scanner(System.in);
System.out.println("请输入你的选择 1.查看所有图书信息 2.购买书籍 3.查询购买记录 4.关闭系统");
try {
int num = sc.nextInt();
switch (num) {
case 1:
LookForLibraryInfo(list);
break;
case 2:
BuyBook(list);
break;
case 3:
FindBuy(buyList);
break;
case 4:
System.exit(WindowConstants.EXIT_ON_CLOSE);
break;
default:
System.out.println("没有这个选项");
main();
break;
}
} catch (Exception e) {
System.out.println("请输入数字,不能输入其它字符~");
main();
}
}
//查询当前用户购买的图书信息
private static void FindBuy(ArrayList<UserBuy> buyList) throws SQLException, ClassNotFoundException {
System.out.println("购买记录如下所示:");
int index = getBuyIndex(buyList, name);
if (index >= 0) {
buyList.stream().forEach(userBuy -> System.out.println("用户" + userBuy.getName() + "于" + userBuy.getBuyTime() + "购买了" + userBuy.getLibraryName()));
} else {
System.out.println("您还没有购买任何书籍");
}
main();
}
//购买书籍
private static void BuyBook(ArrayList<Library> list) throws SQLException, ClassNotFoundException {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入你要购买的图书名字");
String libraryName = sc.next();
int index = getIndex(list, libraryName);
if (index >= 0) {
//图书存在
//判断图书数量是否大于0
Integer count = list.get(index).getCount();
if (count > 0) {
//图书有剩余容量
System.out.println("请输入购买数量:");
Integer amount = sc.nextInt();
//判断购买数量是否在图书库存范围内
if (amount > 0 && amount <= list.get(index).getCount()) {
//在库存范围内
//获取剩余书籍数量
Integer remainingCount = list.get(index).getCount() - amount;
//更新数据库
String sql = "update library set count='" + remainingCount + "'where name='" + libraryName + "'";
Connect.edit(sql);
System.out.println("购买成功!");
//获取当前购买时间
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String datetime = sdf.format(d);
//将用户名和图书名字插入数据库中
Connect.edit("insert into buy_table values ('" + name + "','" + libraryName + "','" + datetime + "')");
main();
break;
} else {
System.out.println("超出库存范围,请重新输入~");
}
} else {
//图书已经卖完了
System.out.println("很抱歉,图书已经卖完了");
System.out.println("是否继续执行图书购买操作?输入yes/no");
String continue1 = "yes";
String exit = "no";
String choose = sc.next();
if (choose.equals(continue1)) {
//继续购买书籍
BuyBook(list);
} else if (choose.equals(exit)) {
UserBuyLibrary.main();
}
}
} else {
System.out.println("不存在该书籍!请重新输入~");
}
}
}
//查询书籍
private static void LookForLibraryInfo(ArrayList<Library> list) throws SQLException, ClassNotFoundException {
System.out.println("图书信息如下:");
list.stream().forEach(new Consumer<Library>() {
@Override
public void accept(Library library) {
System.out.println("图书编号:" + library.getId() + " 图书名字: 《" + library.getName() + "》 图书作者:" + library.getAuthor()
+ " 图书价格:" + library.getPrice() + " 图书库存" + library.getCount() + " 图书上架时间:" + library.getTime());
}
});
main();
}
//判断图书名字在集合在是否存在
public static int getIndex(ArrayList<Library> list, String name) {
for (int i = 0; i < list.size(); i++) {
if (name.equals(list.get(i).getName())) {
return i;
}
}
return -1;
}
//判断用户在是否存在在购买集合中
private static int getBuyIndex(ArrayList<UserBuy> buyList, String name) {
for (int i = 0; i < buyList.size(); i++) {
if (name.equals(buyList.get(i).getName())) {
return i;
}
}
return -1;
}
}
Admin.java
package com.java.main.pojo;
/**
* 管理员实体类
*/
public class Admin extends User {
public Admin() {
}
public Admin(Integer id, String username, String password) {
super(id, username, password);
}
}
Library.java
package com.java.main.pojo;
/**
* 图书实体类
*/
public class Library {
private Integer id;
private String name;
private String author;
private Double price;
private Integer count;
private String time;
public Library() {
}
public Library(Integer id, String name, String author, Double price, Integer count, String time) {
this.id = id;
this.name = name;
this.author = author;
this.price = price;
this.count = count;
this.time = time;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
@Override
public String toString() {
return "Library{" +
"id=" + id +
", name='" + name + '\'' +
", author='" + author + '\'' +
", price=" + price +
", count=" + count +
", time='" + time + '\'' +
'}';
}
}
User.java
package com.java.main.pojo;
/**
* 用户实体类
*/
public class User {
private Integer id;
private String username;
private String password;
public User() {
}
public User(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
UserBuy.java
package com.java.main.pojo;
/**
* 购买记录实体类
*/
public class UserBuy {
private String name;
private String libraryName;
private String buyTime;
public UserBuy() {
}
public UserBuy(String name, String libraryName, String buyTime) {
this.name = name;
this.libraryName = libraryName;
this.buyTime = buyTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLibraryName() {
return libraryName;
}
public void setLibraryName(String libraryName) {
this.libraryName = libraryName;
}
public String getBuyTime() {
return buyTime;
}
public void setBuyTime(String buyTime) {
this.buyTime = buyTime;
}
@Override
public String toString() {
return "UserBuy{" +
"name='" + name + '\'' +
", libraryName='" + libraryName + '\'' +
", buyTime='" + buyTime + '\'' +
'}';
}
}
AppRun.java
package com.java.main.start;
import com.java.main.pojo.Admin;
import com.java.main.pojo.User;
import com.java.main.common.AdminLoginSuccess;
import com.java.main.common.UserBuyLibrary;
import com.java.main.utils.Connect;
import com.java.main.utils.CodeUtil;
import javax.swing.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Scanner;
/**
* @author leiGood浮生若梦
* @since 2024-06-30 星期日 20:50:10
* 博客地址:http://t.csdnimg.cn/hvV9h
* 用户注册登录
* 管理员登录
*/
public class AppRun {
public AppRun() {
System.out.println("******************图书管理系统**********************");
System.out.println("*********************欢迎您!***********************");
System.out.println("******************海内存知己,**********************");
System.out.println("******************天涯若比邻**********************");
}
public static void main(String[] args) throws SQLException, ClassNotFoundException {
new AppRun();
//用户
ArrayList<User> list = new ArrayList<User>();
//管理员
ArrayList<Admin> UserAdmin = new ArrayList<>();
//获取用户
ResultSet rs1 = Connect.queryAll("select * from user");
while (rs1.next()) {
Integer id = rs1.getInt("id");
String username = rs1.getString("username");
String password = rs1.getString("password");
list.add(new User(id, username, password));
}
//获取管理员
ResultSet rs2 = Connect.queryAll("select * from admin");
while (rs2.next()) {
Integer id = rs2.getInt("id");
String username = rs2.getString("username");
String password = rs2.getString("password");
UserAdmin.add(new Admin(id, username, password));
}
Scanner sc = new Scanner(System.in);
rs2.close();
rs1.close();
while (true) {
System.out.println("请输入您的选择:1.登录 2注册 3管理管理员登录 4关闭系统");
String numStr = sc.nextLine();
try {
int num = Integer.parseInt(numStr);
switch (num) {
case 1:
Login(list);
break;
case 2:
Register(list);
break;
case 3:
AdminLogin(UserAdmin);
break;
case 4:
System.exit(WindowConstants.EXIT_ON_CLOSE);
break;
default:
System.out.println("没有这个选项");
break;
}
} catch (Exception e) {
System.out.println("请输入数字,不能输入其它字符");
}
}
}
/**
* 管理员登录
*
* @param UserAdminList
* @throws SQLException
* @throws ClassNotFoundException
*/
private static void AdminLogin(ArrayList<Admin> UserAdminList) throws SQLException, ClassNotFoundException {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入管理员账号");
String username = sc.nextLine();
System.out.println("请输入管理员密码");
String pwd = sc.nextLine();
int adminIndex = getAdminIndex(UserAdminList, username);
if (adminIndex >= 0) {
if (UserAdminList.get(adminIndex).getUsername().equals(username) &&
UserAdminList.get(adminIndex).getPassword().equals(pwd)) {
System.out.println("登录成功!");
new AdminLoginSuccess();
break;
} else {
System.out.println("密码输入错误!");
}
} else {
System.out.println("该用户管理员账号不存在!");
}
}
}
/**
* 用户注册
*
* @param list
* @throws SQLException
* @throws ClassNotFoundException
*/
private static void Register(ArrayList<User> list) throws SQLException, ClassNotFoundException {
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String username = sc.next();
//判断输入的用户名是否符合要求
boolean flag = flag(username);
if (flag) {
//输入的用户名符合
//判断用户名是否存在
int index = getIndex(list, username);
if (index < 0) {
//用户名不存在,可以执行注册
System.out.println("请输入密码:");
String pwd1 = sc.next();
boolean pwdFlag = pwdFlag(pwd1);
if (pwdFlag) {
//符合要求
System.out.println("请再次输入密码:");
String pwd2 = sc.next();
if (pwd2.equals(pwd1)) {
//两次密码输入一致
String sql = "insert into user(username,password) values('" + username + "','" + pwd2 + "')";
Connect.edit(sql);
System.out.println("注册成功!");
//刷新用户集合中的数据,在次进行查询获取用户数据
//获取数据库中的用户
ResultSet rs1 = Connect.queryAll("select * from user");
while (rs1.next()) {
Integer id = rs1.getInt("id");
String uname = rs1.getString("username");
String password = rs1.getString("password");
list.add(new User(id, uname, password));
}
break;
} else {
//两次密码输入不一致
System.out.println("两次密码输入不一致,请重新输入!");
}
} else {
//不符合要求
System.out.println("密码只能由数字和字母组成,最少6位,最多15位");
}
} else {
System.out.println("用户名已经存在,请重新输入~");
}
} else {
//输入的用户名不符合
System.out.println("用户名要求4-10位且全为字母,请重新输入吧");
}
}
}
/**
* 用户登录
*
* @param list
* @throws SQLException
* @throws ClassNotFoundException
*/
private static void Login(ArrayList<User> list) throws SQLException, ClassNotFoundException {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入用户名:");
String username = sc.nextLine();
//判断用户名是否存在
int index = getIndex(list, username);
if (index >= 0) {
//用户名存在,执行下一步输入密码操作
System.out.println("请输入密码:");
String password = sc.nextLine();
if (password.equals(list.get(index).getPassword())) {
String codeStr = CodeUtil.getCode();
System.out.println("当前验证码为:" + codeStr);
System.out.println("请输入验证码:");
String code = sc.nextLine();
if (code.equalsIgnoreCase(codeStr)) {
//密码输入正确
System.out.println("登陆成功!");
//传递用户登录的用户名
new UserBuyLibrary(username).main();
break;
} else {
System.out.println("验证码输入错误,请重新输入");
}
} else {
System.out.println("密码输入错误,请重新输入");
}
} else {
//用户名不存在
System.out.println("用户名未注册,请注册后再来使用~");
break;
}
}
}
/**
* 判断用户在登录或者注册时用户名是否存在,存在返回对应的索引,否则返回-1
*
* @param list
* @param username
* @return
*/
public static int getIndex(ArrayList<User> list, String username) {
for (int i = 0; i < list.size(); i++) {
if (username.equals(list.get(i).getUsername())) {
//存在
return i;
}
}
//不存在
return -1;
}
/**
* 判断管理员登录
*
* @param list
* @param username
* @return
*/
public static int getAdminIndex(ArrayList<Admin> list, String username) {
for (int i = 0; i < list.size(); i++) {
if (username.equals(list.get(i).getUsername())) {
//存在
return i;
}
}
//不存在
return -1;
}
/**
* 用户注册时要求用户名全为字母,最少4位,最多10位
*
* @param username 用户名
* @return 布尔值
*/
public static boolean flag(String username) {
//只能为字母,最少4位,最多10位
String regex = "[a-zA-Z]{4,10}";
return username.matches(regex);
}
/**
* 用户注册时要求密码只能由数字和字母组成,最少6位,最多15位
*
* @param password 用户名
* @return 布尔值
*/
public static boolean pwdFlag(String password) {
//只能为数字和字母,最少6位,最多15位
String regex = "[a-zA-Z0-9]{6,15}";
return password.matches(regex);
}
}
CodeUtil.java
package com.java.main.utils;
import java.util.ArrayList;
import java.util.Random;
/**
* 验证码工具类
*/
public class CodeUtil {
public static String getCode() {
ArrayList<Character> list = new ArrayList<>();
for (int i = 0; i < 26; i++) {
list.add((char) ('a' + i));
}
for (int i = 0; i < 26; i++) {
list.add((char) ('A' + i));
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++) {
int index = new Random().nextInt(list.size());
sb.append(list.get(index));
}
for (int i = 0; i < 2; i++) {
int number = new Random().nextInt(10);
sb.append(number);
}
return sb.toString();
}
}
Connect.java
package com.java.main.utils;
import java.sql.*;
/**
* 数据库连接工具类
*/
public class Connect {
/**
* 查询表中的所有数据
*
* @param sql
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public static ResultSet queryAll(String sql) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection rt = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/lib_dtb", "root", "");
Statement st = rt.createStatement();
ResultSet rs = st.executeQuery(sql);
return rs;
}
/**
* 添加数据,删除数据,修改数据
*
* @param sql
* @throws ClassNotFoundException
* @throws SQLException
*/
public static void edit(String sql) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection rt = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/lib_dtb", "root", "");
Statement st = rt.createStatement();
st.executeUpdate(sql);
}
}