图书管理系统
一、主要实训内容
本次实训主要目的是通过开发一个图书管理系统,运用Java编程语言,Swing和JDBC等技术,实现对图书信息的增删查改等基本功能。实训期间学习并掌握了面向对象程序设计方法、数据库应用、Swing界面设计等知识点。
二、项目情况介绍
1.项目背景
图书管理系统是为图书馆、书店等场所设计的一种信息管理系统。通过该系统,用户能够对图书信息进行录入、查询、修改和删除等操作,有效管理图书信息,提高信息处理效率,满足图书信息管理的需求。
2.研发目的及意义
开发该项目的目的是锻炼对Java编程语言和相关技术的运用能力,提升面向对象编程的理解与实践。图书管理系统的实现能够帮助用户高效管理图书信息,提供了便捷的操作方式,具有一定的实际意义。
3.项目树状图目录展示
│ .gitignore
│ java_swing_librarydemo.iml
│
├─.idea
│ │ .gitignore
│ │ dataSources.local.xml
│ │ dataSources.xml
│ │ misc.xml
│ │ modules.xml
│ │ workspace.xml
│ │
│ ├─dataSources
│ │ │ f995d308-69f9-4969-8e12-603df704cac3.xml
│ │ │
│ │ └─f995d308-69f9-4969-8e12-603df704cac3
│ │ └─storage_v2
│ │ └─_src_
│ │ └─schema
│ │ information_schema.FNRwLQ.meta
│ │ library_system.M5JveQ.meta
│ │ mysql.osA4Bg.meta
│ │ performance_schema.kIw0nw.meta
│ │ sys.zb4BAA.meta
│ │
│ └─libraries
│ mysql_connector_java_5_1_47.xml
│
├─lib
│ mysql-connector-java-5.1.47.jar
│
├─out
│ └─production
│ └─java_swing_librarydemo
│ └─com
│ └─niit
│ │ LibraryMain.class
│ │
│ ├─dao
│ │ │ BookDao.class
│ │ │ LoginDao.class
│ │ │
│ │ └─impl
│ │ BookDaoImpl.class
│ │ LoginDaoImpl.class
│ │
│ ├─entity
│ │ Book.class
│ │
│ ├─listener
│ │ DelectListener.class
│ │ LoginListener.class
│ │ MyMouseListenerAdapter.class
│ │ SaveBookListener.class
│ │ SearchListener.class
│ │ ToSaveBtnListener.class
│ │ ToUpdateListener.class
│ │ UpdateListener.class
│ │
│ ├─utils
│ │ ConnectionUtil.class
│ │ Constants.class
│ │ MD5Util.class
│ │
│ └─view
│ AddBookView$1.class
│ AddBookView.class
│ LoginView.class
│ MainView.class
│
└─src
└─com
└─niit
│ LibraryMain.java
│
├─dao
│ │ BookDao.java
│ │ LoginDao.java
│ │
│ └─impl
│ BookDaoImpl.java
│ LoginDaoImpl.java
│
├─entity
│ Book.java
│
├─listener
│ DelectListener.java
│ LoginListener.java
│ MyMouseListenerAdapter.java
│ SaveBookListener.java
│ SearchListener.java
│ ToSaveBtnListener.java
│ ToUpdateListener.java
│ UpdateListener.java
│
├─utils
│ ConnectionUtil.java
│ Constants.java
│ MD5Util.java
│
└─view
AddBookView.java
LoginView.java
MainView.java
4.事件监听器及适配器和关键类总结
- BookDaoImpl:实现了图书管理的数据访问接口,包括书籍的增删改查操作。
- LoginDaoImpl:处理用户登录相关的数据访问逻辑,验证用户身份。
- Book:表示图书的实体类,包含了书籍的各种属性。
- MainView:主界面视图类,提供了图书管理系统的整体视图。
- AddBookView:用于添加书籍的界面视图。
- LoginView:登录界面视图,处理用户登录。
- ConnectionUtil:提供数据库连接和关闭连接的工具类。
- Constants:包含项目中用到的常量。
- MD5Util:用于密码加密的工具类。
- DelectListener:处理删除操作的事件监听器。
- LoginListener: 处理登录验证的事件监听器。
- MyMouseListenerAdapter: 处理鼠标事件的适配器。
- SaveBookListener: 处理保存书籍信息的事件监听器。
- SearchListener: 处理搜索功能的事件监听器。
- ToSaveBtnListener: 处理点击保存按钮的事件监听器。
- ToUpdateListener: 处理更新操作的事件监听器。
- UpdateListener: 处理更新书籍信息的事件监听器。
- Class CounterProject: 主类
5.项目主界面展示
三、技术路线
- Java编程语言:利用Java实现了系统的后端逻辑。
- Swing界面库:设计了GUI界面,提供了用户友好的交互。
- JDBC数据库连接:实现PreparedStatement预编译的SQL语句防范SQL注入攻击与MySQL数据库的连接与交互。
- IDEA开发工具:用于代码编写、调试和版本控制。
在实训过程中使用了Java编程语言、Swing界面设计工具,以及JDBC连接数据库。开发环境采用了IDEA编译器和DataGrip数据库管理工具。这些技术和工具的应用帮助完成了项目的基本功能和界面设计。
四、需求分析
通过分析项目需求,确定了图书管理系统的基本功能模块,包括图书查询、添加、修改和删除等。用户需求主要集中在对图书信息的便捷操作和查询功能上。
五、概要设计
1.功能模块设计
图书查询模块(支持模糊查询)
图书添加模块
图书修改模块
图书删除模块
2.数据库设计
设计了一个名为sys_book的数据库表,包含图书的ISBN、书名、作者、出版社等信息字段,通过JDBC连接实现与系统的交互。
六、系统实现
1.代码结构和功能实现
在设计上,项目遵循了MVC(Model-View-Controller)模式,将业务逻辑、数据和用户界面分离,提高了代码的可维护性和可扩展性。实现了基本的图书管理功能,包括对图书信息的增删改查操作,并提供了用户登录功能。采用了 Swing 构建用户界面,使用 JDBC 连接数据库进行数据操作。
2.功能展示
提供了用户友好的GUI界面,展示了系统的各项功能操作,包括图书查询、添加、修改和删除等,实现了基本的图书信息管理。
3.实现代码
`Dao层:`
`public class BookDaoImpl implements BookDao {`
`@Override`
`public Vector<Book> bookList(String bookName) {`
`String sql;`
`Connection conn = null;`
`PreparedStatement psmt = null;`
`ResultSet rs = null;`
`Vector<Book> booklist = new Vector<>();`
`sql = "select * from sys_books where 1=1 ";`
`try {`
`conn = ConnectionUtil.**getConnection**();`
`if(bookName!=null&&!bookName.trim().equals("")){`
`bookName="%"+bookName+"%";`
`sql += "and book_name like ?";`
`}`
`psmt = conn.prepareStatement(sql);`
`if(bookName!=null&&!bookName.trim().equals("")){`
`psmt.setString(1, bookName);`
`}`
`rs = psmt.executeQuery();`
`while(rs.next()) {`
`Book book = new Book();`
`book.setId(rs.getInt("id"));`
`book.setBookName(rs.getString("book_name"));`
`book.setBookAuthor(rs.getString("book_author"));`
`book.setBookPublisher(rs.getString("book_publisher"));`
`book.setBookPrice(rs.getDouble("book_price"));`
`book.setCreateTime(rs.getTimestamp("create_time"));`
`booklist.add(book);`
`}`
`} catch (Exception e) {`
`e.printStackTrace();`
`}finally {`
`ConnectionUtil.**close**(conn, psmt, rs);`
`}`
`return booklist;`
`}`
`@Override`
`public void delete(int id) {`
`String sql;`
`Connection conn = null;`
`PreparedStatement psmt = null;`
`Integer rs ;`
`try {`
`sql = "delete from sys_books where id = ? ";`
`conn = ConnectionUtil.**getConnection**();`
`psmt = conn.prepareStatement(sql);`
`psmt.setInt(1, id);`
`rs = psmt.executeUpdate();`
`} catch (Exception e) {`
`e.printStackTrace();`
`}finally {`
`ConnectionUtil.**close**(conn, psmt, null);`
`}`
`}`
`@Override`
`public boolean insertBook(Book book) {`
`Connection conn = null;`
`PreparedStatement psmt = null;`
`ResultSet rs = null;`
`String sql = "insert into sys_books(book_price,book_name,book_author,book_publisher,create_time)"`
`\+ "values (?,?,?,?,?) ";`
`try {`
`conn = ConnectionUtil.**getConnection**();`
`psmt = conn.prepareStatement(sql);`
`psmt.setDouble(1, book.getBookPrice());`
`psmt.setString(2, book.getBookName());`
`psmt.setString(3, book.getBookAuthor());`
`psmt.setString(4, book.getBookPublisher());`
`psmt.setTimestamp(5, book.getCreateTime());`
`psmt.executeUpdate();`
`return true;`
`} catch (Exception e) {`
`e.printStackTrace();`
`}finally {`
`ConnectionUtil.**close**(conn, psmt, rs);`
`}`
`return false;`
`}`
`@Override`
`public void update(Book book) {`
`String sql;`
`Connection conn = null;`
`PreparedStatement psmt = null;`
`Integer rs ;`
`try {`
`sql = "update sys_books set book_price = ?,book_name=?,book_author=?,book_publisher=?,create_time=? where id = ?";`
`conn = ConnectionUtil.**getConnection**();`
`psmt = conn.prepareStatement(sql);`
`psmt.setDouble(1, book.getBookPrice());`
`psmt.setString(2, book.getBookName());`
`psmt.setString(3, book.getBookAuthor());`
`psmt.setString(4, book.getBookPublisher());`
`psmt.setTimestamp(5, book.getCreateTime());`
`psmt.setInt(6, book.getId());`
`rs = psmt.executeUpdate();`
`} catch (Exception e) {`
`e.printStackTrace();`
`}finally {`
`ConnectionUtil.**close**(conn, psmt, null);`
`}`
`}`
`}`
`public class LoginDaoImpl implements LoginDao {`
`@Override`
`public boolean login(String uname, String pwd) {`
`String sql = "select * from sys_user where username = ?";`
`Connection conn = null;`
`PreparedStatement psmt = null;`
`ResultSet rs = null;`
`try {`
`conn = ConnectionUtil.**getConnection**();`
`psmt = conn.prepareStatement(sql);`
`psmt.setString(1, uname);`
`rs = psmt.executeQuery();`
`if(rs.next()) {`
`String dbpwd = rs.getString("pwd");`
`if(pwd.equals(dbpwd))`
`return true;`
`}`
`} catch (Exception e) {`
`e.printStackTrace();`
`}finally {`
`ConnectionUtil.**close**(conn, psmt, rs);`
`}`
`return false;`
`}`
`}`
``
`entity实体类:`
`public class Book {`
`private Integer id;`
`private Double bookPrice;`
`private String bookName;`
`private String bookAuthor;`
`private String bookPublisher;`
`private Timestamp createTime;`
`public Book() {`
`}`
`public Book(Double bookPrice, String bookName, String bookAuthor, String bookPublisher) {`
`super();`
`this.bookPrice = bookPrice;`
`this.bookName = bookName;`
`this.bookAuthor = bookAuthor;`
`this.bookPublisher = bookPublisher;`
`}`
``
`public Book(Integer id, Double bookPrice, String bookName, String bookAuthor, String bookPublisher,`
`Timestamp createTime) {`
`super();`
`this.id = id;`
`this.bookPrice = bookPrice;`
`this.bookName = bookName;`
`this.bookAuthor = bookAuthor;`
`this.bookPublisher = bookPublisher;`
`this.createTime = createTime;`
`}`
`public Integer getId() {`
`return id;`
`}`
`public void setId(Integer id) {`
`this.id = id;`
`}`
`public Double getBookPrice() {`
`return bookPrice;`
`}`
`public void setBookPrice(Double bookPrice) {`
`this.bookPrice = bookPrice;`
`}`
`public String getBookName() {`
`return bookName;`
`}`
`public void setBookName(String bookName) {`
`this.bookName = bookName;`
`}`
`public String getBookAuthor() {`
`return bookAuthor;`
`}`
`public void setBookAuthor(String bookAuthor) {`
`this.bookAuthor = bookAuthor;`
`}`
`public String getBookPublisher() {`
`return bookPublisher;`
`}`
`public void setBookPublisher(String bookPublisher) {`
`this.bookPublisher = bookPublisher;`
`}`
`public Timestamp getCreateTime() {`
`return createTime;`
`}`
`public void setCreateTime(Timestamp createTime) {`
`this.createTime = createTime;`
`}`
`@Override`
`public String toString() {`
`return "Book [id=" + id + ", bookPrice=" + bookPrice + ", bookName=" + bookName + ", bookAuthor=" + bookAuthor`
`\+ ", bookPublisher=" + bookPublisher + ", createTime=" + createTime + "]";`
`}`
`}`
`listener监听类:`
`public class DelectListener extends MouseAdapter{`
`private MainView view;`
`private BookDao dao ;`
`public DelectListener(MainView view){`
`this.view = view;`
`dao = new BookDaoImpl();`
`}`
`//当点击删除时`
`@Override`
`public void mouseClicked(MouseEvent arg0) {`
`JTable dataTable = view.getDataTable();`
`int selectedColumn = dataTable.getSelectedColumn();`
`int row = dataTable.getSelectedRow();`
`//拿到选中行的id值`
`int value = (int) dataTable.getValueAt(row, 0);`
`dao.delete(value);`
`System.**out**.println("删除ID号"+value+"数据成功");`
`view.dispose();`
`new MainView(null);`
`}`
`}`
`**/******
** ***** **登录按钮的点击事件****`
`** ***/****`
`**public class LoginListener extends MouseAdapter{
private LoginView view;
private LoginDao dao ;
public LoginListener(LoginView loginView) {
this.view = loginView;
dao = new LoginDaoImpl();
}
@Override
public void mouseClicked(MouseEvent e) {
String uname = view.getUserNameTextField().getText();
String pwd = new String(view.getPwdTextField().getPassword());
if(null != uname && !uname.trim().equals("") ) {
String pwMD5 = MD5Util.**encrypt**(pwd);
boolean flag = dao.login(uname, pwMD5);
if(flag) {
new MainView(null);
view.dispose();
}else {
JOptionPane.**showMessageDialog**(null, "用户名或密码错误");
}
}else {
JOptionPane.**showMessageDialog**(null, "用户名不能为空");`
`return;`
`}`
`}`
`}`
`鼠标监听适配器:`
`public class MyMouseListenerAdapter extends MouseAdapter{`
`AddBookView view;`
`public void setView(AddBookView view) {`
`this.view = view;`
`}`
`}`
`**/******
** ***** **保存书籍****`
`** *******`
`** ***/****`
`**public class SaveBookListener extends MyMouseListenerAdapter {`
`private BookDao bookDao;`
`public SaveBookListener() {`
`this.bookDao = new BookDaoImpl();`
`}`
`@Override`
`public void mouseClicked(MouseEvent e) {`
`String bookName = view.getBookNameTextField().getText();`
`String bookPrice = view.getBookPriceTextField().getText();`
`String bookAuthor = view.getBookAuthorTextField().getText();`
`String bookPublisher = view.getBookPublisherTextField().getText();`
`Book book = new Book(Double.**parseDouble**(bookPrice), bookName, bookAuthor, bookPublisher);`
`book.setCreateTime(new Timestamp(System.**currentTimeMillis**()));`
`boolean flag = bookDao.insertBook(book);`
`if (flag) {`
`JOptionPane.**showMessageDialog**(null, "添加成功");`
`} else {`
`JOptionPane.**showMessageDialog**(null, "添加失败");`
`}`
`new MainView(null);`
`view.dispose();`
`}`
`}`
`搜索类:`
`public class SearchListener extends MouseAdapter {`
`private MainView view;`
`private BookDao dao ;`
`public SearchListener(MainView view){`
`this.view = view;`
`this.dao = new BookDaoImpl();`
`}`
`//当点击查询时执行此方法`
`@Override`
`public void mouseClicked(MouseEvent e) {`
`//获取要查询的书名`
`String bookName = view.getBookNameTextField().getText();`
`//select * from sys_books where book_name like "%java%";`
`Vector<Book> bookList = dao.bookList(bookName);`
`System.**out**.println(bookList);`
`Vector<Vector> v = new Vector<Vector>();`
`for(Book b : bookList) {`
`Vector ve = new Vector();`
`ve.add(b.getId());`
`ve.add(b.getBookName());`
`ve.add(b.getBookAuthor());`
`ve.add(b.getBookPrice());`
`ve.add(b.getBookPublisher());`
`ve.add(b.getCreateTime());`
`ve.add("修改");`
`ve.add(new JButton("删除"));`
`v.add(ve);`
`}`
`view.dispose();`
`new MainView(v);`
`}`
`}`
`保存书籍:`
`public class ToSaveBtnListener extends MouseAdapter {`
`private MainView view;`
`public ToSaveBtnListener(MainView view) {`
`this.view = view;`
`}`
`@Override`
`public void mouseClicked(MouseEvent e) {`
`SaveBookListener listener = new SaveBookListener();`
`new AddBookView("新增",listener);`
`this.view.dispose();`
`}`
`}`
`修改书籍:`
`public class ToUpdateListener extends MouseAdapter{`
`private MainView view;`
`private BookDao dao ;`
`public ToUpdateListener(MainView view){`
`this.view = view;`
`this.dao = new BookDaoImpl();`
`}`
`//点击修改后`
`@Override`
`public void mouseClicked(MouseEvent e) {`
`System.**out**.println("点击修改后");`
`JTable dataTable = view.getDataTable();`
`int row = dataTable.getSelectedRow();`
`// 确保有选中的行`
`if (row >= 0) {`
`Object[] oArray = new Object[6];`
`for (int i = 0; i < 6; i++) {`
`Object v = dataTable.getValueAt(row, i);`
`oArray[i] = v;`
`}`
`Book b = new Book((Integer) oArray[0], (Double) oArray[3], (String) oArray[1], (String) oArray[2], (String) oArray[4], (Timestamp) oArray[5]);`
`UpdateListener listener = new UpdateListener(b);`
`new AddBookView("修改", listener);`
`this.view.dispose();`
`} else {`
`// 如果没有选中行,可能需要给出提示或采取其他操作`
`System.**out**.println("请选择要修改的行");`
`}`
`}`
`}`
`提交监听:`
`public class UpdateListener extends MyMouseListenerAdapter {`
`private BookDao bookDao;`
`private Book b;`
`public Book getB() {`
`return b;`
`}`
`public UpdateListener(Book b) {`
`this.bookDao = new BookDaoImpl();`
`this.b = b;`
`}`
`@Override`
`public void mouseClicked(MouseEvent e) {`
`System.**out**.println("点击提交后");`
`Book b = view.getBook();`
`String bookName = view.getBookNameTextField().getText();`
`String bookPrice = view.getBookPriceTextField().getText();`
`String bookAuthor = view.getBookAuthorTextField().getText();`
`String bookPublisher = view.getBookPublisherTextField().getText();`
`Book book = new Book(b.getId(),Double.**parseDouble**(bookPrice), bookName, bookAuthor, bookPublisher,new Timestamp(System.**currentTimeMillis**()));`
`bookDao.update(book);`
`new MainView(null);`
`view.dispose();`
`}`
`}`
`Utils工具类:`
`数据库连接和关闭连接的工具类:`
`public class ConnectionUtil {`
`private static final String **DRIVER** = "com.mysql.jdbc.Driver";`
`private static final String **URL** = "jdbc:mysql://localhost:3306/library_system?useUnicode=true&characterEncoding=UTF-8";`
`private static final String **USERNAME** = "root";`
`private static final String **PASSWORD** = "123456";`
`public static Connection getConnection() {`
`Connection conn = null;`
`try {`
`Class.**forName**(**DRIVER**);`
`conn = DriverManager.**getConnection**(**URL**, **USERNAME**,**PASSWORD**);`
`} catch (Exception e) {`
`JOptionPane.**showMessageDialog**(null, "数据库连接失败");`
`e.printStackTrace();`
`}`
`return conn;`
`}`
`public static void close(Connection conn,PreparedStatement psmt, ResultSet rs) {`
`**closeConnection**(conn);`
`**closeStatement**(psmt);`
`**closeResultSet**(rs);`
`}`
`private static void closeConnection(Connection conn){`
`if(conn != null) {`
`try {`
`conn.close();`
`} catch (SQLException e) {`
`e.printStackTrace();`
`}`
`}`
`}`
`private static void closeResultSet(ResultSet rs){`
`if(rs != null) {`
`try {`
`rs.close();`
`} catch (SQLException e) {`
`e.printStackTrace();`
`}`
`}`
`}`
`private static void closeStatement(Statement pstm){`
`if(pstm != null) {`
`try {`
`pstm.close();`
`} catch (SQLException e) {`
`e.printStackTrace();`
`}`
`}`
`}`
`}`
``
`常量工具类:`
`public class Constants {`
`public static final String **FONT_STYLE** = "微软雅黑";`
`}`
`密码加密的工具类:`
`public class MD5Util {`
`public static String encrypt(String dataStr) {`
`try {`
`MessageDigest m = MessageDigest.**getInstance**("MD5");`
`m.update(dataStr.getBytes("UTF8"));`
`byte s[] = m.digest();`
`String result = "";`
`for (int i = 0; i < s.length; i++) {`
`result += Integer.**toHexString**((0x000000FF & s[i]) | 0xFFFFFF00).substring(6);`
`}`
`return result;`
`} catch (Exception e) {`
`e.printStackTrace();`
`}`
`return "";`
`}`
`}`
### 4.数据库核心代码
`· create table sys_books`
`·`
`· //创建一个sys_books的表存储关于图书的数据库表`
`(`
`id int auto_increment`
`primary key,`
`book_price double null comment '价格',`
`book_name varchar(100) null,`
`book_author varchar(20) null,`
`book_publisher varchar(100) null,`
`create_time datetime null`
`)`
`charset = utf8mb3; //这指定了该表的字符集为utf8mb3,这是一个支持多字节字符的UTF-8字符集`
`create table sys_user //表存储关于用户信息的数据库表`
`(`
`id int auto_increment`
`primary key,//主键`
`username varchar(50) null,`
`pwd varchar(64) null, //这是一个最大长度为64的变长字符串字段,用于存储用户密码。通常在实际应用中,为了安全,密码应该被加密存储而不是明文`
`create_time datetime null //这是一个日期时间字段,用于存储记录创建的时间`
`)`
`charset = utf8mb3; //这指定了该表的字符集为utf8mb3,这是一个支持多字节字符的UTF-8字符集`
------
## 七、总结与展望
.printStackTrace();`
`}`
`return "";`
`}`
`}`
### 4.数据库核心代码
`· create table sys_books`
`·`
`· //创建一个sys_books的表存储关于图书的数据库表`
`(`
`id int auto_increment`
`primary key,`
`book_price double null comment '价格',`
`book_name varchar(100) null,`
`book_author varchar(20) null,`
`book_publisher varchar(100) null,`
`create_time datetime null`
`)`
`charset = utf8mb3; //这指定了该表的字符集为utf8mb3,这是一个支持多字节字符的UTF-8字符集`
`create table sys_user //表存储关于用户信息的数据库表`
`(`
`id int auto_increment`
`primary key,//主键`
`username varchar(50) null,`
`pwd varchar(64) null, //这是一个最大长度为64的变长字符串字段,用于存储用户密码。通常在实际应用中,为了安全,密码应该被加密存储而不是明文`
`create_time datetime null //这是一个日期时间字段,用于存储记录创建的时间`
`)`
`charset = utf8mb3; //这指定了该表的字符集为utf8mb3,这是一个支持多字节字符的UTF-8字符集`
七、总结与展望
在项目开发过程中遇到了数据库连接问题,通过查阅文档和向同学请教解决了问题。通过这次实训,更加深入了解了Java编程语言,C/S模式和相关技术的应用。在未来的学习中,计划进一步学习Web开发和其他Java技术,提升自己的编程水平,收获颇多!