声明:本项目不涉及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;
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 {
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[]{
new ExitOperation(),
new DisplayOperation(),
new FindOperation(),
new BorrowOperation(),
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(){
this.operations = new IOperation[]{
new ExitOperation(),
new DisplayOperation(),
new FindOperation(),
new AddOperation(),
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;
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;
private static DataSource getDataSource(){
if(dataSource == null){
dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setUrl(URL);
((MysqlDataSource)dataSource).setUser(USERNAME);
((MysqlDataSource)dataSource).setPassword(PASSWORD);
}
return dataSource;
}
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;
public class BookDao {
public boolean add(Book book){
Connection connection = null;
PreparedStatement statement = null;
try {
connection = DBUtil.getConnection();
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);
int ret = statement.executeUpdate();
if(ret == 1)
return true;
return false;
}catch (SQLException e){
e.printStackTrace();
}finally {
DBUtil.close(connection,statement,null);
}
return false;
}
public List<Book> selectAll() {
List<Book> list = new ArrayList<>();
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = DBUtil.getConnection();
String sql = "select * from book";
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
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;
}
public List<Book> selectByName(String name){
List<Book> list = new ArrayList<>();
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = DBUtil.getConnection();
String sql = "select * from book where name=?";
statement = connection.prepareStatement(sql);
statement.setString(1,name);
resultSet = statement.executeQuery();
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;
}
public boolean delete(int bookId){
Connection connection = null;
PreparedStatement statement = null;
try {
connection = DBUtil.getConnection();
String sql = "delete from book where bookId=?";
statement = connection.prepareStatement(sql);
statement.setInt(1,bookId);
int ret = statement.executeUpdate();
if(ret != 1){
return false;
}
return true;
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(connection,statement,null);
}
return false;
}
public boolean borrowBook(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()){
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=1 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;
}
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()){
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()){
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.1:AddOperation类:增加书籍
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();
List<Book> books = 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();
List<Book> books = 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) {
User user = login();
while(true){
int choice = user.menu();
user.doOperation(choice);
}
}
private static User login() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用户名:");
String userName = scanner.next();
System.out.println("请输入密码:");
String passWord = scanner.next();
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.管理员操作
|