Mysql實(shí)戰(zhàn)練習(xí)之簡(jiǎn)單圖書管理系統(tǒng)
一、梳理功能
1.能夠表示書籍信息,針對(duì)每本書來(lái)說(shuō),序號(hào),書名,作者,價(jià)格,類型。
2.能夠表示用戶信息,普通用戶,管理員。
3.支持的操作:
- 對(duì)于普通用戶:查看書籍列表,查詢指定書籍,借書還書。
- 對(duì)于 管理員:查看書籍列表,新增刪除書籍。

二、準(zhǔn)備數(shù)據(jù)庫(kù)
創(chuàng)建用戶表和書籍表
create database if not exists java100_bookmanager;
use java100_bookmanager;
drop table if exists book;
//設(shè)置id為自增主鍵
create table book(id int primary key auto_increment,name varchar(20),author varchar(20),price int,type varchar(20),isBorrowed int);
drop table if exists user;
//同樣設(shè)置 userid為自增主鍵并且用戶名字不重復(fù)
create table user(
userId int primary key auto_increment,
username varchar(20) unique,
password varchar(20),
isAdmin int
);
-- 插入一些書籍
insert into book values(null,'西游記','吳承恩',10000,'古典小說(shuō)',0);
insert into book values(null,'三國(guó)演義','羅貫中',10000,'古典小說(shuō)',0);
insert into book values(null,'水滸傳','施耐庵',10000,'古典小說(shuō)',0);
insert into book values(null,'金瓶梅','蘭陵笑笑生',10000,'古典小說(shuō)',0);
--插入一些用戶
insert into user values(null,'admin','123',1);
insert into user values(null,'zhangsan','123',0);
三、構(gòu)造和數(shù)據(jù)庫(kù)相關(guān)的實(shí)體類
書籍
public class Books {
private int bookId;//書籍編號(hào)
private String name;//書名
private String author;//作者
private int price;//價(jià)格
private String type;//類型
private boolean isBorrowed;//是否被借閱
//set get方法
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 +
'}';
}
用戶
有兩種用戶,一種為普通用戶,另一種為管理員,管理員和普通用戶看到的menu不同,管理員和普通 用戶的類方法也不同
先定義一個(gè)抽象類User 讓普通用戶NoramlUser和管理員類Admin來(lái)繼承User類
abstract public class user {
private int userId;
private String userName;
private String passWord;
IOperation[] operations;//方法數(shù)組,表示user類所包含的方法
abstract int menu();//子類要重寫menu方法,因?yàn)閮蓚€(gè)子類看到的menu不同
public void doOperation(int choice){//此方法來(lái)執(zhí)行一些操作,如借書還書等
operations[choice].work();
}
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 + '\'' +
'}';
}
}
NormalUser類
public class NormalUser extends user{
public NormalUser(){
this.operations=new IOperation[]{//之后單獨(dú)開辟一個(gè)包,包里存儲(chǔ)和實(shí)現(xiàn)這些方法
new ExitOperation(),//退出系統(tǒng)
new DisplayOperation(),//查看書籍列表
new FindOperation(),//查找書籍
new BorrowOperation(),//借閱書籍
new ReturnOperation(),//還書
};
}
@Override
public int menu() {//重寫父類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.退出系統(tǒng)");
System.out.println("========================");
System.out.println("請(qǐng)輸入選項(xiàng)");
Scanner sc=new Scanner(System.in);
int choice=sc.nextInt();
return choice;
}
}
Admin類
public class Admin extends user {
public Admin(){
this.operations=new IOperation[]{
new ExitOperation(),//退出系統(tǒng)
new DisplayOperation(),//查看書籍列表
new FindOperation(),//查找書籍
new AddOperation(),//添加書籍
new DelOperation(),//刪除書籍
};
}
@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.退出系統(tǒng)");
System.out.println("========================");
System.out.println("請(qǐng)輸入選項(xiàng)");
Scanner sc=new Scanner(System.in);
int choice=sc.nextInt();
return choice;
}
}
四、封裝數(shù)據(jù)庫(kù)相關(guān)操作
- 1.先把數(shù)據(jù)庫(kù)鏈接的操作封裝好
- 2.再把針對(duì)書籍表的增刪查改操作封裝好
- 3.再把針對(duì)用戶表的操作封裝好
數(shù)據(jù)庫(kù)鏈接操作
//在這里封裝數(shù)據(jù)庫(kù)的連接操作
public class DBUtil {
//設(shè)置url 賬號(hào)密碼 根據(jù)個(gè)人設(shè)置
private static final String URL="jdbc:mysql://127.0.0.1:3306/java100_bookmanager?characterEncoding=utf8&&useSSL=false";
private static final String USERNAME="root";
private static final String PASSWORD="q986681563";
//餓漢模式
//類加載階段就會(huì)調(diào)用靜態(tài)代碼塊進(jìn)行實(shí)例化
/*private static DataSource dataSource=new MysqlDataSource();
static{
((MysqlDataSource)dataSource).setUrl(URL);
((MysqlDataSource)dataSource).setUser(USERNAME);
((MysqlDataSource)dataSource).setPassword(PASSWORD);
}*/
//懶漢模式
//只有首次調(diào)用getDataSource方法 才會(huì)實(shí)例化
private static DataSource dataSource=null;
public 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(ResultSet resultSet, PreparedStatement statement,Connection connection){//釋放資源
//注釋掉的方式更安全
/*if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}*/
try {
if(resultSet!=null) resultSet.close();
if(statement!=null) statement.close();
if(connection!=null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
針對(duì)書籍表操作
//DAO Data Access Object 數(shù)據(jù)訪問(wèn)對(duì)象
public class BookDAO {
//1.新增書籍
public boolean add(Books 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 false;
return true;
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(null,statement,connection);
}
return false;
}
//2.查看所有書籍
public List<Books> selectAll(){
List<Books> 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()){
Books book=new Books();
book.setBookId(resultSet.getInt("id"));
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(resultSet,statement,connection);
}
return list;
}
//3.根據(jù)名字找書籍
public List<Books> selectByName(String name) {
List<Books> 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()){
Books book=new Books();
book.setBookId(resultSet.getInt("Id"));
book.setName(resultSet.getString("name"));
book.setAuthor(resultSet.getString("author"));
book.setType(resultSet.getString("type"));
book.setPrice(resultSet.getInt("price"));
book.setBorrowed(resultSet.getInt("isBorrowed")==1);
list.add(book);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(resultSet,statement,connection);
}
return list;
}
//4.刪除書籍
public boolean delete(int bookId){
Connection connection=null;
PreparedStatement statement=null;
try {
connection=DBUtil.getConnection();
String sql="delete from book where id=?";
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(null,statement,connection);
}
return false;
}
//5.借書
public boolean borrowBook(int bookId){
Connection connection=null;
PreparedStatement statement=null;
PreparedStatement statement2=null;
ResultSet resultSet=null;
try {
connection=DBUtil.getConnection();
String sql="select * from book where id=?";
statement=connection.prepareStatement(sql);
statement.setInt(1,bookId);
resultSet=statement.executeQuery();
if(resultSet.next()){
boolean isBorrowed=(resultSet.getInt("isBorrowed")==1);
if(isBorrowed){
System.out.println("書已借出,無(wú)法再次借出! bookId="+bookId);
return false;
}
}else{
System.out.println("書不存在 bookId="+bookId);
return false;
}
sql="update book set isBorrowed=1 where id=?";
statement2=connection.prepareStatement(sql);
statement2.setInt(1,bookId);
int ret = statement2.executeUpdate();
if(ret!=1) {
System.out.println("借閱失敗");
return false;
}
System.out.println("借閱成功");
return true;
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(resultSet!=null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(statement!=null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(statement2!=null) {
try {
statement2.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return false;
}
//6.歸還
public boolean returnBook(int bookId){
Connection connection=null;
PreparedStatement statement=null;
PreparedStatement statement2=null;
ResultSet resultSet=null;
try {
connection=DBUtil.getConnection();
String sql="select* from book where id=?";
statement=connection.prepareStatement(sql);
statement.setInt(1,bookId);
resultSet= statement.executeQuery();
if(resultSet.next()){
boolean isBorrowed=(resultSet.getInt("isBorrowed")==1);
if(!isBorrowed){
System.out.println("書沒(méi)有被借出,不需要?dú)w還 bookId="+bookId);
return false;
}
}else{
System.out.println("沒(méi)有該書! bookId="+bookId);
return false;
}
sql="update book set isBorrowed=0 where id=?";
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 {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(statement!=null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(statement2!=null) {
try {
statement2.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return false;
}
}

針對(duì)用戶表的操作
public class UserDao {
//根據(jù)用戶名找密碼的邏輯
//username是unique約束的
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 users=null;
if(isAdmin){
users=new Admin();
}else users=new NormalUser();
users.setPassWord(resultSet.getString("password"));
users.setUserId(resultSet.getInt("userId"));
users.setUserName(resultSet.getString("username"));
return users;
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(resultSet,statement,connection);
}
return null;
}
}
編寫主邏輯(main方法和login方法)
public class Main {
public static void main(String[] args) {
user users=login();
while(true){
int choice=users.menu();
users.doOperation(choice);
}
}
private static user login(){
Scanner sc=new Scanner(System.in);
System.out.println("請(qǐng)輸入用戶名");
String name=sc.next();
System.out.println("請(qǐng)輸入密碼");
String password=sc.next();
UserDao userDao=new UserDao();
user users=userDao.selectByName(name);
if(users==null){
System.out.println("登陸失?。?);
System.exit(0);
}
if(!users.getPassWord().equals(password)){
System.out.println("密碼錯(cuò)誤");
System.exit(0);
}
return users;
}
}
編寫operation各種細(xì)節(jié)
將所有operations操作放在一個(gè)包中,定義一個(gè)接口operations,所有操作實(shí)現(xiàn)這個(gè)接口并重寫方法
IOperation接口
public interface IOperation {
void work();
}
添加書籍操作
public class AddOperation implements IOperation{
@Override
public void work() {
System.out.println("新增書籍!");
Scanner sc=new Scanner(System.in);
System.out.println("請(qǐng)輸入書名");
String name=sc.next();
System.out.println("請(qǐng)輸入作者");
String author=sc.next();
System.out.println("請(qǐng)輸入價(jià)格");
int price=sc.nextInt();
System.out.println("請(qǐng)輸入類別");
String type=sc.next();
Books book=new Books();
book.setName(name);
book.setPrice(price);
book.setType(type);
book.setAuthor(author);
BookDAO bookDAO=new BookDAO();
boolean ret=bookDAO.add(book);
if(ret) System.out.println("新增成功");
else System.out.println("新增失敗");
}
}
借書操作
public class BorrowOperation implements IOperation {
@Override
public void work() {
System.out.println("借閱書籍");
System.out.println("請(qǐng)輸入要借閱的書籍id");
Scanner sc=new Scanner(System.in);
int id=sc.nextInt();
BookDAO bookDAO=new BookDAO();
boolean ret = bookDAO.borrowBook(id);
}
}
刪除書籍操作
public class DelOperation implements IOperation{
@Override
public void work() {
System.out.println("刪除書籍!");
Scanner sc=new Scanner(System.in);
System.out.println("請(qǐng)輸入刪除書籍的id");
int id=sc.nextInt();
BookDAO bookDAO=new BookDAO();
boolean ret = bookDAO.delete(id);
if(ret) System.out.println("刪除成功");
else System.out.println("刪除失敗");
}
}
查看書籍列表操作
public class DisplayOperation implements IOperation {
@Override
public void work() {
System.out.println("展示所有書籍");
BookDAO bookdao=new BookDAO();
List<Books> list=bookdao.selectAll();
for(Books book:list){
System.out.println(book);
}
System.out.println("展示書籍完畢");
}
}
退出系統(tǒng)操作
public class ExitOperation implements IOperation{
@Override
public void work() {
System.out.println("退出程序");
System.exit(0);
}
}
查找書籍操作
public class FindOperation implements IOperation{
@Override
public void work() {
System.out.println("根據(jù)名字查找書籍");
System.out.println("請(qǐng)輸入書名");
Scanner sc=new Scanner(System.in);
String name=sc.next();
BookDAO bookDAO=new BookDAO();
List<Books> books = bookDAO.selectByName(name);
for(Books book:books){
System.out.println(book);
}
System.out.println("根據(jù)名字查找書籍完畢");
}
}
還書操作
public class ReturnOperation implements IOperation{
@Override
public void work() {
System.out.println("歸還書籍!");
System.out.println("請(qǐng)輸入要?dú)w還的書籍的id");
Scanner sc=new Scanner(System.in);
int id=sc.nextInt();
BookDAO bookDAO=new BookDAO();
boolean ret = bookDAO.returnBook(id);
if(ret){
System.out.println("歸還成功");
}else{
System.out.println("歸還失敗");
}
}
}
總結(jié):簡(jiǎn)單的圖書管理系統(tǒng),通過(guò)練習(xí)掌握簡(jiǎn)單JDBC語(yǔ)法和API,同時(shí)可以幫助理解java中多態(tài)繼承等概念。
到此這篇關(guān)于Mysql實(shí)戰(zhàn)練習(xí)之簡(jiǎn)單圖書管理系統(tǒng)的文章就介紹到這了,更多相關(guān)Mysql 圖書管理系統(tǒng)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入淺析MySQL從刪庫(kù)到跑路_高級(jí)(一)——數(shù)據(jù)完整性
數(shù)據(jù)完整性是指數(shù)據(jù)的可靠性和準(zhǔn)確性,數(shù)據(jù)完整性類型有四種,本文給大家提到,接下來(lái)通過(guò)本文給大家介紹MySQL從刪庫(kù)到跑路的內(nèi)容分析,感興趣的朋友跟隨小編一起看看吧2018-11-11
MySQL9.0的兩種部署模式及各個(gè)版本發(fā)布的新功能
本文主要介紹了MySQL9.0的兩種部署模式及各個(gè)版本發(fā)布的新功能,文中通過(guò)圖文示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-08-08
Win10 MySQL如何解決secure_file_priv在my.ini無(wú)法設(shè)置問(wèn)題
這篇文章主要介紹了Win10 MySQL如何解決secure_file_priv在my.ini無(wú)法設(shè)置問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-04-04
MYSQL 數(shù)據(jù)庫(kù)命名與設(shè)計(jì)規(guī)范
對(duì)于MYSQL 數(shù)據(jù)庫(kù)的命名與設(shè)計(jì),需要一定的規(guī)范,所以我們要了解和快速的掌握mysql有很多的幫助。2008-12-12
mysqldump進(jìn)行數(shù)據(jù)備份詳解
這篇文章主要介紹了mysqldump進(jìn)行數(shù)據(jù)備份詳解,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以慘一下2022-07-07

