明确对像
- 书
- 用户 - - - - - - 管理员用户 + 普通用户
- 书架(即数据库) - - - - - - 书表 + 用户表
明确对象结构
明确需求
建表
drop table if exists book;
drop table if exists user;
create table book(bookId int primary key auto_increment,
name varchar(20),
author varchar(20),
type varchar(20),
-- 1表示已借出,0表示未借出
isBorrowed int);
create table user(userId int primary key auto_increment,
name varchar(20) unique,
password varchar(20),
-- 1表示是管理员,0表示不是管理员
isAmin int );
insert into book values(null, "西游记","吴承恩","神话小说",0);
insert into book values(null,"平凡的世界","路遥","陕北风情",0);
insert into user values(null, "东仔","1234",1);
insert into user values(null, "辉仔","1234",0);
创建对象
- Book类
/**
* Created with IntelliJ IDEA.
* Description:
* User: 强仔
* Date: 2022-01-26
* Time: 16:08
*/
public class Book {
private int bookId;
private String name;
private String author;
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 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 + '\'' +
", type='" + type + '\'' +
", isBorrowed=" + isBorrowed +
'}';
}
}
- User类
不需要创建实例,所以User可以创建成抽象类
其子类为 NormalUser 和 Amin,只需要其子类创建实例即可
子类不需要继承User的成员变量,只需要重写其work()方法即可
abstract public class User {
private int userId;
private String name;
private String password;
boolean isAmin;
Operation[] operations = null;
abstract public void work();
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isAmin() {
return isAmin;
}
public void setAmin(boolean amin) {
isAmin = amin;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", name='" + name + '\'' +
", isAmin=" + isAmin +
", operations=" + Arrays.toString(operations) +
'}';
}
}
- Amin类
public class Amin extends User{
//可进行的操作
Operation[] operations = {
new ExitOp(),
new SelectOp(),
new SelectByNameOp(),
new InsertOp(),
new DeleteOp()
};
@Override
void work() {
}
}
- NormalUser类
public class NormalUser extends User{
//可进行的操作
Operation[] operations = {
new ExitOp(),
new SelectOp(),
new SelectByNameOp(),
new BorrowOp(),
new ReturnOp()
};
@Override
void work() {
}
}
- Operation接口及实现此接口的操作类
public interface Operation {
void operate();
}
- DBUtil类 把数据库的 连接和创建sql语句 操作封装一下
一个工程只要一个数据源就好
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 String url = "jdbc:mysql://127.0.0.1:3306/bookmanage?characterEncoding=utf8&useSSL=false";
private static String userName = "root";
private static String password = "cuige2001";
private static DataSource dataSource = new MysqlDataSource();
private Connection connection = null;
//静态代码块 类加载时执行,只执行一次,在main方法前
//1.创建数据库源
static {
((MysqlDataSource) dataSource).setUrl(url);
((MysqlDataSource) dataSource).setUser(userName);
((MysqlDataSource) dataSource).setPassword(password);
}
//实例代码块 构造方法执行前执行,构造方法执行多少次,它就执行多少次
//2.建立连接
{
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
//3.构造sql语句
public PreparedStatement preparedStatement(String sql) throws SQLException {
return connection.prepareStatement(sql);
}
//5.释放资源
public void close(PreparedStatement statement, ResultSet resultSet){
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
- BookDao类 对数据库书表的所有操作
注意
resultSet.next() 和 resultSet == null 的区别
ResultSet resultSet
resultSet.next() //false
resultSet == null // false
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BookDao {
//新增书籍
public static boolean Insert(Book book) {
DBUtil dbUtil = new DBUtil();
PreparedStatement statement = null;
try {
String sql = "insert into book values(null,?,?,?,0)";
statement = dbUtil.preparedStatement(sql);
statement.setString(1, book.getName());
statement.setString(2, book.getAuthor());
statement.setString(3, book.getType());
int ret = statement.executeUpdate();
return ret == 1;
} catch (SQLException e) {
e.printStackTrace();
} finally {
dbUtil.close(statement, null);
}
return false;
}
//查看所有书籍
public static void Select() {
DBUtil dbUtil = new DBUtil();
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
String sql = "select * from book";
statement = dbUtil.preparedStatement(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.setType(resultSet.getString("type"));
boolean ret = resultSet.getInt("isBorrowed") == 1;
book.setBorrowed(ret);
System.out.println(book);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
dbUtil.close(statement, resultSet);
}
}
//根据书名查找书籍
public static void SelectByName(String name) {
DBUtil dbUtil = new DBUtil();
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
String sql = "select * from book where name = ?";
statement = dbUtil.preparedStatement(sql);
statement.setString(1, name);
resultSet = statement.executeQuery();
//标记
boolean sign = true;
while(resultSet.next()) {
sign = false;
Book book = new Book();
book.setBookId(resultSet.getInt("bookId"));
book.setName(resultSet.getString("name"));
book.setAuthor(resultSet.getString("author"));
book.setType(resultSet.getString("type"));
boolean ret = resultSet.getInt("isBorrowed") == 1;
book.setBorrowed(ret);
System.out.println(book);
}
if (sign){
System.out.println("查无此书!!!");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
dbUtil.close(statement, resultSet);
}
}
//删除书籍
public static boolean Delete(int bookId) {
DBUtil dbUtil = new DBUtil();
PreparedStatement statement = null;
try {
String sql = "delete from book where bookId = ?";
statement = dbUtil.preparedStatement(sql);
statement.setInt(1, bookId);
int ret = statement.executeUpdate();
if (ret == 1) {
System.out.println("删除成功!!!");
return true;
} else {
System.out.println("删除失败,没有此书!!!");
return false;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
dbUtil.close(statement, null);
}
return false;
}
//借书
public static boolean Borrow(int bookId) {
DBUtil dbUtil = new DBUtil();
PreparedStatement statement = null;
PreparedStatement statement2 = null;
ResultSet resultSet = null;
try {
String sql = "select * from book where bookId = ?";
statement = dbUtil.preparedStatement(sql);
statement.setInt(1,bookId);
resultSet = statement.executeQuery();
if (resultSet.next()) {
boolean isBorrowed = resultSet.getInt("isBorrowed") == 1;
if (isBorrowed) {
System.out.println("已经借出去了!!!");
return false;
} else {
String str = "Update book set isBorrowed = 1 where bookId = ?";
statement2 = dbUtil.preparedStatement(str);
statement2.setInt(1,bookId);
statement2.executeUpdate();
System.out.println("借书成功!!!");
return true;
}
} else {
System.out.println("没有此书!!!");
return false;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if(statement2 != null) {
try {
statement2.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
dbUtil.close(statement, resultSet);
}
return false;
}
//还书
public static boolean Return(int bookId) {
DBUtil dbUtil = new DBUtil();
PreparedStatement statement = null;
PreparedStatement statement2 = null;
ResultSet resultSet = null;
try {
String sql = "select * from book where bookId = ?";
statement = dbUtil.preparedStatement(sql);
statement.setInt(1,bookId);
resultSet = statement.executeQuery();
if (resultSet.next()) {
boolean isBorrowed = resultSet.getInt("isBorrowed") == 1;
if (!isBorrowed) {
System.out.println("此书已还!!!");
return false;
} else {
String str = "Update book set isBorrowed = 0 where bookId = ?";
statement2 = dbUtil.preparedStatement(str);
statement2.setInt(1,bookId);
statement2.executeUpdate();
System.out.println("还书成功!!!");
return true;
}
} else {
System.out.println("没有此书!!!");
return false;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if(statement2 != null) {
try {
statement2.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
dbUtil.close(statement, resultSet);
}
return false;
}
}
- UserDao类 对数据库用户表的所有操作
package Other;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDao {
//根据用户名查找用户信息
public static User findUser(String name){
DBUtil dbUtil = new DBUtil();
PreparedStatement statement = null;
ResultSet resultSet = null;
User user = null;
try {
String sql = "select * from user where name = ?";
statement = dbUtil.preparedStatement(sql);
statement.setString(1,name);
resultSet = statement.executeQuery();
if(resultSet.next()) {
boolean isAmin = resultSet.getInt("isAmin") == 1;
if (isAmin) {
user = new Amin();
} else {
user = new NormalUser();
}
user.setUserId(resultSet.getInt("userId"));
user.setName(resultSet.getString("name"));
user.setPassword(resultSet.getString("password"));
user.setAmin(isAmin);
}
} catch (SQLException e) {
e.printStackTrace();
}
finally {
dbUtil.close(statement,resultSet);
}
return user;
}
//新增普通用户
public static boolean InsertNormal(User user) {
DBUtil dbUtil = new DBUtil();
PreparedStatement statement = null;
try {
String sql = "insert into user values(null,?,?,0)";
statement = dbUtil.preparedStatement(sql);
statement.setString(1, user.getName());
statement.setString(2, user.getPassword());
int ret = statement.executeUpdate();
return ret == 1;
} catch (SQLException e) {
e.printStackTrace();
} finally {
dbUtil.close(statement, null);
}
return false;
}
//查看所有用户
public static void Select() {
DBUtil dbUtil = new DBUtil();
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
String sql = "select * from user";
statement = dbUtil.preparedStatement(sql);
resultSet = statement.executeQuery();
while (resultSet.next()) {
boolean ret = resultSet.getInt("isAmin") == 1;
User user = null;
if(ret){
user = new Amin();
user.setAmin(ret);
}else{
user = new NormalUser();
user.setAmin(ret);
}
user.setUserId(resultSet.getInt("userId"));
user.setName(resultSet.getString("name"));
System.out.println(user);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
dbUtil.close(statement, resultSet);
}
}
//修改密码
public static boolean UpdatePassword(String password, int userId){
DBUtil dbUtil = new DBUtil();
PreparedStatement statement = null;
try {
String sql = "Update user set password = ? where userId = ?";
statement = dbUtil.preparedStatement(sql);
statement.setString(1,password);
statement.setInt(2,userId);
int ret = statement.executeUpdate();
if(ret == 1){
System.out.println("修改成功!!!");
return true;
}else{
System.out.println("修改失败!!!");
return false;
}
} catch (SQLException e) {
e.printStackTrace();
}
finally {
dbUtil.close(statement,null);
}
return false;
}
//删除用户
public static boolean Delete(int userId) {
DBUtil dbUtil = new DBUtil();
PreparedStatement statement = null;
PreparedStatement statement2 = null;
ResultSet resultSet = null;
try {
String str = "select * from user where userId = ?";
statement = dbUtil.preparedStatement(str);
statement.setInt(1,userId);
resultSet = statement.executeQuery();
if(!resultSet.next()){
System.out.println("没有此用户");
return false;
}
boolean ret = resultSet.getInt("isAmin") == 1;
if(ret){
System.out.println("大胆,怎敢删管理员!!!");
return false;
}
String sql = "delete from user where userId = ? ";
statement2 = dbUtil.preparedStatement(sql);
statement2.setInt(1, userId);
statement2.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
} finally {
if(statement2 != null){
try {
statement2.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
dbUtil.close(statement, resultSet);
}
return false;
}
}
实现业务
-
User类中添加 menu()抽象方法
NormalUser类中 重写menu() 和 work()
Amin中重写 menu() 和 work() -
此处将work()变为work(int ret),为了用户选择操作
work(int ret, int uesrId) 为了用户修改密码操作 -
Test类
import Op.InsetNormalOp;
import Op.Operation;
import Op.UpdatewordOp;
import Other.User;
import Other.UserDao;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("---1.注册新用户 ---2.已有用户");
int biu = scanner.nextInt();
if(biu == 1){
Operation op = new InsetNormalOp();
op.operate();
}
System.out.println("请输入用户名");
String name = scanner.next();
System.out.println("请输入密码");
String password = scanner.next();
User user = UserDao.findUser(name);
if (user == null) {
System.out.println("滚蛋!!!");
System.exit(0);
}
if (!password.equals(user.getPassword())) {
System.out.println("滚蛋!!!");
System.exit(0);
}
while (true) {
user.menu();
System.out.println("请输入要进行的操作序号:");
int ret = scanner.nextInt();
user.work(ret,user.getUserId());
}
}
}
- User类
package Other;
import Op.Operation;
abstract public class User {
private int userId;
private String name;
private String password;
boolean isAmin;
Operation[] operations = null;
abstract public void work(int ret, int userId);
abstract public void menu();
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isAmin() {
return isAmin;
}
public void setAmin(boolean amin) {
isAmin = amin;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", name='" + name + '\'' +
", isAmin=" + isAmin +
'}';
}
}
- NormalUser类
package Other;
import Op.*;
public class NormalUser extends User{
//可进行的操作
Operation[] operations = {
new ExitOp(),
new SelectOp(),
new SelectByNameOp(),
new BorrowOp(),
new ReturnOp()
};
@Override
public void work(int ret, int userId) {
if(ret == 5){
UpdatewordOp.operate(userId);
return;
}
if(ret < 0 || ret >= operations.length){
System.out.println("输入错误!!!");
return;
}
operations[ret].operate();
}
@Override
public void menu() {
System.out.println("=================");
System.out.println(" 0.退出");
System.out.println(" 1.查看所有书籍 ");
System.out.println(" 2.根据书名查找书籍");
System.out.println(" 3.借书");
System.out.println(" 4.还书");
System.out.println(" 5.修改密码");
System.out.println("=================");
}
}
- Amin类
package Other;
import Op.*;
public class Amin extends User {
//可进行的操作
Operation[] operations = {
new ExitOp(),
new SelectOp(),
new SelectByNameOp(),
new InsertOp(),
new DeleteOp(),
new SelectUsersOp(),
new SelectUsersByNameOp(),
new DeleteUserOp()
};
@Override
public void work(int ret, int userId) {
if(ret == 8){
UpdatewordOp.operate(userId);
return;
}
if (ret < 0 || ret >= operations.length) {
System.out.println("输入错误!!!");
return;
}
operations[ret].operate();
}
@Override
public void menu() {
System.out.println("=================");
System.out.println(" 0.退出");
System.out.println(" 1.查看所有书籍 ");
System.out.println(" 2.根据书名查找书籍");
System.out.println(" 3.新增书籍");
System.out.println(" 4.删除书籍");
System.out.println(" 5.查看所有用户");
System.out.println(" 6.根据名字查找用户");
System.out.println(" 7.删除用户");
System.out.println(" 8.修改密码");
System.out.println("=================");
}
}
完善OP包中的各类操作
- BorrowOp
借书
package Op;
import Other.BookDao;
import java.util.Scanner;
public class BorrowOp implements Operation{
@Override
public void operate() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入所借图书的Id");
int id = scanner.nextInt();
Boolean ret = BookDao.Borrow(id);
if(ret){
System.out.println("借书成功!!!");
}else{
System.out.println("借书失败!!!");
}
}
}
- DeleteOp
删除书籍
package Op;
import Other.BookDao;
import java.util.Scanner;
public class DeleteOp implements Operation {
@Override
public void operate() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入所要删除的图书的Id:");
int id = scanner.nextInt();
BookDao.Delete(id);
}
}
- DeleteUserOp
删除用户
package Op;
import Other.UserDao;
import java.util.Scanner;
public class DeleteUserOp implements Operation{
@Override
public void operate() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入删除的用户的Id:");
int id = scanner.nextInt();
boolean ret = UserDao.Delete(id);
if(ret){
System.out.println("删除成功!!!");
}else{
System.out.println("删除失败!!!");
}
}
}
- ExitOp
退出程序
package Op;
public class ExitOp implements Operation {
@Override
public void operate() {
System.exit(0);
}
}
- InsertOp
新增书籍
package Op;
import Other.Book;
import Other.BookDao;
import java.util.Scanner;
public class InsertOp implements Operation {
@Override
public void operate() {
Book book = new Book();
Scanner scanner = new Scanner(System.in);
System.out.println("请输入新书的name:");
book.setName(scanner.next());
System.out.println("请输入新书的作者:");
book.setAuthor(scanner.next());
System.out.println("请输入新书的类型:");
book.setType(scanner.next());
Boolean ret = BookDao.Insert(book);
if(ret){
System.out.println("新增成功!!!");
}else{
System.out.println("新增失败!!!");
}
}
}
- InsetNormalOp
新增普通用户
package Op;
import Other.NormalUser;
import Other.User;
import Other.UserDao;
import java.util.Scanner;
public class InsetNormalOp implements Operation {
@Override
public void operate() {
Scanner scanner = new Scanner(System.in);
String name = null;
while (true) {
System.out.println("用户名:");
name = scanner.next();
if (UserDao.findUser(name) == null) {
break;
}
System.out.println("该用户名已存在,请重新输入");
}
System.out.println("请输入密码:");
User user = new NormalUser();
user.setName(name);
user.setPassword(scanner.next());
boolean ret = UserDao.InsertNormal(user);
if(ret){
System.out.println("添加成功!!");
}else{
System.out.println("添加失败!!");
}
}
}
- ReturnOp
还书
package Op;
import Other.BookDao;
import java.util.Scanner;
public class ReturnOp implements Operation {
@Override
public void operate() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入所还书的Id");
int id = scanner.nextInt();
Boolean ret = BookDao.Return(id);
if(!ret){
System.out.println("还书失败!!!");
}
}
}
- SelectByNameOp
根据书名查找图书
package Op;
import Other.BookDao;
import java.util.Scanner;
public class SelectByNameOp implements Operation {
@Override
public void operate() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入书的名字:");
String name = scanner.next();
BookDao.SelectByName(name);
}
}
- SelectOp
查看所有图书
package Op;
import Other.BookDao;
public class SelectOp implements Operation {
@Override
public void operate() {
BookDao.Select();
}
}
- SelectUsersByNameOp
根据用户名查找用户
package Op;
import Other.User;
import Other.UserDao;
import java.util.Scanner;
public class SelectUsersByNameOp implements Operation{
@Override
public void operate() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入要查找的用户名:");
String name = scanner.next();
User user = UserDao.findUser(name);
if(user == null){
System.out.println("无此用户");
}else{
System.out.println(user);
}
}
}
- SelectUsersOp
查看所有用户
package Op;
import Other.User;
import Other.UserDao;
import java.util.Scanner;
public class SelectUsersOp implements Operation{
@Override
public void operate() {
UserDao.Select();
}
}
- UpdatewordOp
修改密码
package Op;
import Other.UserDao;
import java.util.Scanner;
public class UpdatewordOp{
public static void operate(int userId) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入修改的密码:");
String password1 = null;
while(true) {
password1 = scanner.next();
System.out.println("在输入一次:");
String password2 = scanner.next();
if (!password1.equals(password2)) {
System.out.println("两次不一致!!!");
System.out.println("请重新输入");
}else{
break;
}
}
UserDao.UpdatePassword(password1,userId);
}
}