声明:本项目不涉及web操作,但需要了解java的基本语法和MySQL的基本语句运用。
一、项目分布
- db.sql类:SQL语句,在控制台执行,用于建立图书管理库。
- Book类: 定义了书的一些属性(书编号,书名,作者,价格,分类,状态)并且写了属性的get、set、toSting方法。
- User类:定义了用户的一些属性(用户编号,用户名,密码和是否为管理员的标记),并且写了属性的get、set、toSting方法。
- NormalUser类:描述普通用户,实现普通用户的构造方法,并打印普通用户的操作界面。
- Admin类:描述管理员,实现管理员的构造方法并打印管理员的操作界面。
- DBUtil类:封装与数据库建立连接的操作(主要用JDBC来编写)。
- BookDao类:封装 对表的增删查改操作。
- UserDao类:封装 识别用户的操作。
operations包中定义了IOperation(操作)接口,这个包中的下面这些类都实现了这个IOperation接口(完成增删查改等操作):
- AddOperation类:增加书籍
- BorrowOperation类:借阅书籍
- DeleteOperation类:删除书籍
- DisplayOperation类:查看书籍列表
- ExitOperation类:退出系统
- FindOperation类:查找书籍
- ReturnOperation类:返还书籍
二、代码展示
1.SQL语句
在控制台执行,用于建立图书管理库(设置“张三”为普通用户,密码为321;“admin”为管理员,密码为123)
create database if not exists bookmanager; use bookmanager; -- 创建一个书籍表 drop table if exists book; create table book( bookId int primary key auto_increment, name varchar(20), author varchar(20), -- 为了准确,价格以 分 为单位 price int, type varchar(20), -- 如果isBorrowed为1,表示已经借出,为0,表示未借出 isBorrowed int ); -- 创建一个用户表(用户有管理员和普通用户两种) drop table if exists user; create table user( userId int primary key auto_increment, username varchar(20) unique, password varchar(20), -- 如果isAdmin 为1,表示是管理员,为0,表示是普通用户 isAdmin int ); -- 插入一些数据 insert into book values(null,'西游记','吴承恩',10000,'古典小说',0); insert into book values(null, '三国演义', '罗贯中', 10000, '古典小说', 0); insert into book values(null, '水浒传', '施耐庵', 10000, '古典小说', 0); insert into book values(null, '金瓶梅', '兰陵笑笑生', 10000, '古典小说', 0); insert into book values(null,'三体','刘慈欣',10000,'科幻小说',0); -- 插入一些用户 insert into user values(null,'admin','123',1); insert into user values(null,'张三','321',0);
2.Book类
定义了书的一些属性(书编号,书名,作者,价格,分类,状态)并且写了属性的get、set、toSting方法
package Java100_1006; //使用这个类来表示一本书 // +------------+-------------+------+-----+---------+----------------+ // | Field | Type | Null | Key | Default | Extra | // +------------+-------------+------+-----+---------+----------------+ // | bookId | int(11) | NO | PRI | NULL | auto_increment | // | name | varchar(20) | YES | | NULL | | // | author | varchar(20) | YES | | NULL | | // | price | int(11) | YES | | NULL | | // | type | varchar(20) | YES | | NULL | | // | isBorrowed | int(11) | YES | | NULL | | // +------------+-------------+------+-----+---------+----------------+ public class Book { private int bookId; private String name; private String author; private int price; private String type; private boolean isBorrowed; public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } 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 int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isBorrowed() { return isBorrowed; } public void setBorrowed(boolean borrowed) { isBorrowed = borrowed; } @Override public String toString() { return "Book{" + "bookId=" + bookId + ", name='" + name + '\'' + ", author='" + author + '\'' + ", price=" + price + ", type='" + type + '\'' + ", isBorrowed=" + isBorrowed + '}'; } }
3.User类
定义了用户的一些属性(用户编号,用户名,密码和是否为管理员的标记),并且写了属性的get、set、toSting方法
package Java100_1006; import Java100_1006.operations.IOperation; abstract public class User { // 使用这个 User 类来表示一个用户 // +----------+-------------+------+-----+---------+----------------+ // | Field | Type | Null | Key | Default | Extra | // +----------+-------------+------+-----+---------+----------------+ // | userId | int(11) | NO | PRI | NULL | auto_increment | // | username | varchar(20) | YES | | NULL | | // | password | varchar(20) | YES | | NULL | | // | isAdmin | int(11) | YES | | NULL | | // +----------+-------------+------+-----+---------+----------------+ // 针对此处的 isAdmin, 并不是直接使用一个 boolean 变量来区分, 而是使用两个不同的子类. // 原因是, 管理员和普通用户支持的方法, 是不一样的. private int userId; private String userName; private String passWord; // 包含了一个数组, 数组里面就是该用户支持的哪些操作. // 针对普通用户, 和管理员, 分别设置不同的操作. IOperation[] operations; //普通用户和管理员看到的菜单也不同 abstract public int menu(); public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } 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{" + "userId=" + userId + ", userName='" + userName + '\'' + ", passWord='" + passWord + '\'' + '}'; } }
4.用户分为两种
普通用户和管理员,所以应该分别建立两个类来描述这两个用户。
4.1NormalUser类
**描述普通用户,实现普通用户的构造方法,并打印普通用户的操作界面。
package Java100_1006; import Java100_1006.operations.*; import java.util.Scanner; //普通用户 public class NormalUser extends User{ //普通用户的构造方法 public NormalUser(){ this.operations = new IOperation[]{ //0.退出 new ExitOperation(), //1.查看书籍列表 new DisplayOperation(), //2. 查找指定书籍 new FindOperation(), //3.借阅书籍 new BorrowOperation(), //4. 归还书籍 new ReturnOperation() }; } //打印普通用户的菜单 @Override public int menu() { System.out.println("============================="); System.out.println("欢迎您"+this.getUserName()+"!"); System.out.println("1. 查看书籍列表"); System.out.println("2. 查找指定书籍"); System.out.println("3. 借阅书籍"); System.out.println("4. 归还书籍"); System.out.println("0. 退出系统"); System.out.println("============================="); System.out.println("请输入您的选项:"); Scanner scanner = new Scanner(System.in); int choice = scanner.nextInt(); return choice; } }
4.2Admin类
描述管理员,实现管理员的构造方法并打印管理员的操作界面
package Java100_1006; import Java100_1006.operations.*; import java.util.Scanner; //管理员 public class Admin extends User{ //管理员的构造方法 public Admin(){ //初始化operation //继承与User类,所以可以使用父类的中的数组 this.operations = new IOperation[]{ //0. 退出系统 new ExitOperation(), //1. 查看书籍列表 new DisplayOperation(), //2. 查找指定书籍 new FindOperation(), //3. 新增书籍 new AddOperation(), //4. 删除书籍 new DeleteOperation() }; } //打印管理员的菜单 @Override public int menu() { System.out.println("================================"); System.out.println("欢迎您, " + this.getUserName() + "! 您是管理员! "); System.out.println("1. 查看书籍列表"); System.out.println("2. 查找指定书籍"); System.out.println("3. 新增书籍"); System.out.println("4. 删除书籍"); System.out.println("0. 退出系统"); System.out.println("================================"); System.out.println("请输入选项: "); Scanner scanner = new Scanner(System.in); int choice = scanner.nextInt(); return choice; } }
5.DBUtil类
封装与数据库建立连接的操作(主要用JDBC来编写)
package Java100_1006; import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; //先建立这个类来 封装 数据库建立连接的操作 //具体步骤: //1.创建DataSouse实例 //2.根据DataSouse创建对应的Connection public class DBUtil { private static final String URL = "jdbc:mysql://127.0.0.1:3306/bookmanager?characterEncoding=utf8&useSSL=false"; private static final String USERNAME = "root"; private static final String PASSWORD = "1234"; //懒汉模式: private static DataSource dataSource = null; //初始情况下,dataSource为null,没有被实例化 //首次调用getDataSource()时才会被实例化 private static DataSource getDataSource(){ if(dataSource == null){ dataSource = new MysqlDataSource(); ((MysqlDataSource)dataSource).setUrl(URL); ((MysqlDataSource)dataSource).setUser(USERNAME); ((MysqlDataSource)dataSource).setPassword(PASSWORD); } return dataSource; } //提供一个方法来建立连接 //用static来修饰,那么就无需实例化DBUtil实例就能调用这个方法,更加方便 public static Connection getConnection() throws SQLException { return getDataSource().getConnection(); } //释放资源 public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet){ try{ if(resultSet != null){ resultSet.close(); } if(statement != null){ statement.close(); } if(connection != null){ connection.close(); } }catch (SQLException e){ e.printStackTrace(); } } }
6.BookDao类
封装 对表的增删查改操作
package Java100_1006; import Java100_1006.Book; import Java100_1006.DBUtil; import java.sql.*; import java.util.ArrayList; import java.util.List; //封装 对Book表的增删查改操作 public class BookDao { //1.新增书籍(插入) public boolean add(Book book){ //把book对象插入数据库的书籍表中 Connection connection = null; PreparedStatement statement = null; try { //1.和数据库建立连接 connection = DBUtil.getConnection(); //2.拼装sql语句 String sql = "insert into book values(null,?,?,?,?,?)"; statement = connection.prepareStatement(sql); statement.setString(1,book.getName()); statement.setString(2,book.getAuthor()); statement.setInt(3,book.getPrice()); statement.setString(4,book.getType()); statement.setInt(5,book.isBorrowed()?1:0); //3.执行SQL int ret = statement.executeUpdate(); if(ret == 1) return true; return false; }catch (SQLException e){ e.printStackTrace(); }finally { DBUtil.close(connection,statement,null); } return false; } //2.查找所有书籍(查找) public ListselectAll() { List list = new ArrayList<>(); Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; try { //1.与数据库建立连接 connection = DBUtil.getConnection(); //2.拼装SQL String sql = "select * from book"; statement = connection.prepareStatement(sql); //3.执行SQL resultSet = statement.executeQuery(); //4.遍历结果集合 while(resultSet.next()){ //取出当前行的这些列,构造一个Book对象来 Book book = new Book(); book.setBookId(resultSet.getInt("bookId")); book.setName(resultSet.getString("name")); book.setAuthor(resultSet.getString("author")); book.setPrice(resultSet.getInt("price")); book.setType(resultSet.getString("type")); book.setBorrowed(resultSet.getInt("isBorrowed")==1); //把这个book对象添加到链表中 list.add(book); } } catch (SQLException e) { e.printStackTrace(); }finally { DBUtil.close(connection,statement,resultSet); } return list; } //3.根据名字查找书籍(查找) public List selectByName(String name){ List list = new ArrayList<>(); Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; try { //1.先与数据库建立连接 connection = DBUtil.getConnection(); //2.拼装SQL语句 String sql = "select * from book where name=?"; statement = connection.prepareStatement(sql); statement.setString(1,name); //3.执行SQL resultSet = statement.executeQuery(); //4.遍历结果集合 while(resultSet.next()){ Book book = new Book(); book.setBookId(resultSet.getInt("bookId")); book.setName(resultSet.getString("name")); book.setAuthor(resultSet.getString("author")); book.setPrice(resultSet.getInt("price")); book.setType(resultSet.getString("type")); book.setBorrowed(resultSet.getInt("isBorrowed") == 1); list.add(book); } } catch (SQLException e) { e.printStackTrace(); }finally { DBUtil.close(connection,statement,resultSet); } return list; } //4.删除书籍(删除) public boolean delete(int bookId){ Connection connection = null; PreparedStatement statement = null; try { //1.建立连接 connection = DBUtil.getConnection(); //2.拼装SQL String sql = "delete from book where bookId=?"; statement = connection.prepareStatement(sql); statement.setInt(1,bookId); //3.执行SQL int ret = statement.executeUpdate(); if(ret != 1){ return false; } return true; } catch (SQLException e) { e.printStackTrace(); }finally { DBUtil.close(connection,statement,null); } return false; } //5.借书(修改) public boolean borrowBook(int bookId){ Connection connection = null; //statement1用于查找操作 PreparedStatement statement1 = null; //statement2用于修改操作 PreparedStatement statement2 = null; ResultSet resultSet = null; try { //1.建立连接 connection = DBUtil.getConnection(); //要借书,就必须知道这本书存不存在,所以我们先查找,再操作 //2.拼装SQL String sql = "select * from book where bookId=?"; statement1 = connection.prepareStatement(sql); statement1.setInt(1,bookId); //3.执行SQL resultSet = statement1.executeQuery(); //4.遍历结果,预期结果要么是1条,要么是0条 if(resultSet.next()){ //进入if就说明书是存在的 boolean isBorrowed = (resultSet.getInt("isBorrowed")==1); if(isBorrowed) { //说明书已经被借出了,不能再次借阅 System.out.println("书已经借出! 无法再次借出! bookId = " + bookId); return false; } }else{ //进入else,那么书是不存在的 System.out.println("书不存在! 无法借出! bookId = " + bookId); return false; } //[接下来是开始进行借书逻辑] //5.拼装SQL sql = "update book set isBorrowed=1 where bookId=?"; statement2 = connection.prepareStatement(sql); statement2.setInt(1,bookId); //6.执行SQL int ret = statement2.executeUpdate(); if(ret != 1){ return false; } return true; } catch (SQLException e) { e.printStackTrace(); }finally { if(resultSet != null){ try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if(statement2 != null){ try { statement2.close(); } catch (SQLException e) { e.printStackTrace(); } } if(statement1 != null){ try { statement1.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } return false; } //6.还书(修改) public boolean returnBook(int bookId){ Connection connection = null; PreparedStatement statement1 = null; PreparedStatement statement2 = null; ResultSet resultSet = null; try { connection = DBUtil.getConnection(); //查询书是否存在 String sql = "select * from book where bookId=?"; statement1 = connection.prepareStatement(sql); statement1.setInt(1,bookId); resultSet = statement1.executeQuery(); if(resultSet.next()){ //进入if语句就说明这本书存在于书籍名单中 boolean isBorrowed = (resultSet.getInt("isBorrowed")==1); if(!isBorrowed){ System.out.println("书没有借出, 没必要还! bookId = " + bookId); return false; } }else{ //不是图书系统中的书,不需要还 System.out.println("书不存在, 无法归还! bookId = " + bookId); return false; } //[还书] //修改书籍的借出状态就可 sql = "update book set isBorrowed=0 where bookId=?"; statement2 = connection.prepareStatement(sql); statement2.setInt(1,bookId); int ret = statement2.executeUpdate(); if(ret != 1){ return false; } return true; } catch (SQLException e) { e.printStackTrace(); }finally { if(resultSet != null){ try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if(statement2 != null){ try { statement2.close(); } catch (SQLException e) { e.printStackTrace(); } } if(statement1 != null){ try { statement1.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } return false; } }
7.UserDao类
封装 识别用户的操作
package Java100_1006; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class UserDao { //实现根据用户名找密码这样一个过程(用户名 唯一) public User selectByName(String name){ Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; try { connection = DBUtil.getConnection(); String sql = "select * from user where username=?"; statement = connection.prepareStatement(sql); statement.setString(1,name); resultSet = statement.executeQuery(); if(resultSet.next()){ //存在这个用户,返回一个User对象 //判断这个用户是普通用户还是管理员 boolean isAdmin = (resultSet.getInt("isAdmin"))==1; User user = null; if (isAdmin){ user = new Admin(); }else{ user = new NormalUser(); } user.setUserId(resultSet.getInt("userId")); user.setUserName(resultSet.getString("username")); user.setPassWord(resultSet.getString("password")); return user; } } catch (SQLException e) { e.printStackTrace(); }finally { DBUtil.close(connection,statement,resultSet); } return null; } }
8.operations包
创建IOperation接口和实现这个接口的其他类
接口:
package Java100_1006.operations; //后续的增加 删除 借书 还书 等操作都要实现这个接口 public interface IOperation { void work(); }
8.1AddOperation类:增加书籍
package Java100_1006.operations; import Java100_1006.Book; import Java100_1006.BookDao; import java.util.Scanner; public class AddOperation implements IOperation{ @Override public void work() { System.out.println("新增书籍!"); Scanner scanner = new Scanner(System.in); System.out.println("请输入书名: "); String bookName = scanner.next(); System.out.println("请输入作者: "); String author = scanner.next(); System.out.println("请输入价格:"); int price = scanner.nextInt(); System.out.println("请输入类别:"); String type = scanner.next(); //假设新增书籍都是未借出的状态 Book book = new Book(); book.setName(bookName); book.setAuthor(author); book.setPrice(price); book.setType(type); BookDao bookDao = new BookDao(); boolean ret = bookDao.add(book); if(ret){ System.out.println("新增书籍成功"); }else{ System.out.println("新增书籍失败!"); } } }
8.2BorrowOperation类:借阅书籍
package Java100_1006.operations; import Java100_1006.BookDao; import java.util.Scanner; public class BorrowOperation implements IOperation{ @Override public void work() { System.out.println("借阅书籍!"); Scanner scanner = new Scanner(System.in); System.out.println("请输入要借阅的书籍id:"); int bookId = scanner.nextInt(); BookDao bookDao = new BookDao(); boolean ret = bookDao.borrowBook(bookId); if (ret) { System.out.println("借阅书籍成功!"); } else { System.out.println("借阅书籍失败!"); } } }
8.3DeleteOperation类:删除书籍
package Java100_1006.operations; import Java100_1006.BookDao; import java.util.Scanner; public class DeleteOperation implements IOperation{ @Override public void work() { System.out.println("删除书籍!"); Scanner scanner = new Scanner(System.in); System.out.println("请输入要删除的书籍id: "); int bookId = scanner.nextInt(); BookDao bookDao = new BookDao(); boolean ret = bookDao.delete(bookId); if (ret) { System.out.println("删除成功!"); } else { System.out.println("删除失败!"); } } }
8.4DisplayOperation类:查看书籍列表
package Java100_1006.operations; import Java100_1006.Book; import Java100_1006.BookDao; import java.util.List; public class DisplayOperation implements IOperation{ @Override public void work() { System.out.println("展示所有书籍!"); BookDao bookDao = new BookDao(); Listbooks = bookDao.selectAll(); for(Book book:books){ System.out.println(book); } System.out.println("展示所有书籍完毕!"); } }
8.5ExitOperation类:退出系统
package Java100_1006.operations; //退出操作 public class ExitOperation implements IOperation{ @Override public void work() { System.out.println("退出程序"); System.exit(0); } }
8.6FindOperation类:查找书籍
package Java100_1006.operations; import Java100_1006.Book; import Java100_1006.BookDao; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class FindOperation implements IOperation{ @Override public void work() { System.out.println("根据名字查找书籍!"); System.out.println("请输入要查找的书名: "); Scanner scanner = new Scanner(System.in); String bookName = scanner.next(); BookDao bookDao = new BookDao(); Listbooks = bookDao.selectByName(bookName); for(Book book:books){ System.out.println(book); } System.out.println("根据名字查找书籍完毕!"); } }
8.7ReturnOperation类:返还书籍
package Java100_1006.operations; import Java100_1006.BookDao; import java.util.Scanner; public class ReturnOperation implements IOperation{ @Override public void work() { System.out.println("归还书籍!"); Scanner scanner = new Scanner(System.in); System.out.println("请输入要归还的书籍id:"); int bookId = scanner.nextInt(); BookDao bookDao = new BookDao(); boolean ret = bookDao.returnBook(bookId); if (ret) { System.out.println("归还书籍成功!"); } else { System.out.println("归还书籍失败!"); } } }
9.Main方法实现
package Java100_1006; import java.util.Scanner; //编写系统的主体逻辑 public class Main { public static void main(String[] args) { //通过login方法进行登录 User user = login(); while(true){ int choice = user.menu(); user.doOperation(choice); } } private static User login() { //1.实现用户登录逻辑 Scanner scanner = new Scanner(System.in); System.out.println("请输入用户名:"); String userName = scanner.next(); System.out.println("请输入密码:"); String passWord = scanner.next(); //2.从数据库根据用户名查询密码 UserDao userDao = new UserDao(); User user = userDao.selectByName(userName); if(user == null){ //不存在该用户 System.out.println("登陆失败!"); // 直接退出程序 System.exit(0); } if(!user.getPassWord().equals(passWord)){ //密码不正确 System.out.println("登陆失败"); System.exit(0); } return user; } }
三、结果实现
1.登录界面
2.普通用户操作
3.管理员操作
到此这篇关于Java开发实例之图书管理系统的实现的文章就介绍到这了,更多相关Java 图书管理内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!