目錄
前言
數據表的建立
操作包各個類的實現
增加類
刪除類
展示類
借閱與歸還類
前言
書接上文
JDBC編程的學習——MYsql版本-CSDN博客
本期我們通過對先前圖書管理系統進行改造,是它的數據能保存在數據庫中
完整代碼我已經保存在github中,能不能給個星呢!!!!
calljsh/MyJava (github.com)
這是先前的圖書管理系統,這篇博客里面也有完整代碼
圖書管理系統(java) 代碼展示和思路介紹 (9000字小長文)_圖書管理系統關鍵代碼展示-CSDN博客
數據表的建立
即為簡易圖書管理系統,我只用了一張表來儲存書的信息,包括書名,作者名,價格,類型,以及是否借出 的State.
這是我們表的結構
mysql> desc lib;
+--------+-------------+------+-----+--------------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+--------------+-------+
| name | varchar(20) | YES | | NULL | |
| author | varchar(20) | YES | | NULL | |
| price | int | YES | | NULL | |
| type | varchar(20) | YES | | NULL | |
| state | varchar(20) | YES | | 未被借出 | |
+--------+-------------+------+-----+--------------+-------+
具體創建的代碼如下
create table lib (name varchar(20),author varchar(20),price int,type varchar(20),state varchar(20) default '未被借出');
我們給我們的狀態列設置默認值——未被借出?
好的現在我們的表建好了
操作包各個類的實現
整個圖書管理系統的邏輯在之前的博客中已經詳細介紹過,只要操作包中的各個類有區別,這也是我需要介紹的實例.
增加類
增加類就是寫好我們需要增加書籍的信息,然后通過SQL語句使數據庫執行
還是基礎的五步,大致為:
創建數據源
建立鏈接
寫好sql語句并執行
處理結果集
釋放資源
package Operation;
import Book.BOOK;
import Book.BookList;
import com.mysql.cj.jdbc.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class Add implements WORK
{@Overridepublic void work(BookList bookList)throws SQLException{//1 創建DataSource dataSource=new MysqlDataSource();((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/jsh?characterEncoding=utf8&useSSL=false");((MysqlDataSource)dataSource).setUser("root");((MysqlDataSource)dataSource).setPassword("你的密碼");//2 建立鏈接Connection connection=dataSource.getConnection();//3 創建sql語句System.out.println("增加圖書");Scanner scanner=new Scanner(System.in);System.out.println("請輸入您要添加的圖書的書名:");String name= scanner.nextLine();System.out.println("請輸入您要添加的圖書的作者名:");String author = scanner.nextLine();System.out.println("請輸入您要添加的圖書的類型:");String type = scanner.nextLine();System.out.println("請輸入您要添加的圖書的價格:");int price = scanner.nextInt();String sql="insert into lib (name,author,price,type,state)values(?,?,?,?,default)";PreparedStatement preparedStatement=connection.prepareStatement(sql);preparedStatement.setString(1,name);preparedStatement.setString(2,author);preparedStatement.setInt(3,price);preparedStatement.setString(4,type);//4 發送給服務器int n=preparedStatement.executeUpdate();//5 釋放資源preparedStatement.close();connection.close();}
}
?有一個要點需要注意,為了能夠讓狀態(state)能夠是我們設置好的默認值,我指定了列,如果有更好的寫法歡迎分享
刪除類
刪除類其實和增加類是一樣的,但是我用了try-catch-finally結構寫給讀者們看
try {// 建立連接connection = dataSource.getConnection();// 獲取用戶輸入Scanner sc = new Scanner(System.in);System.out.println("輸入你要刪除圖書的名字:");String name = sc.nextLine();// 創建SQL語句String sql = "DELETE FROM lib WHERE name = ?";preparedStatement = connection.prepareStatement(sql);preparedStatement.setString(1, name);// 執行刪除操作int rowsAffected = preparedStatement.executeUpdate();if (rowsAffected > 0) {System.out.println("圖書刪除成功");} else {System.out.println("沒有找到要刪除的圖書");}} catch (SQLException e) {e.printStackTrace();
} finally {// 關閉資源if (preparedStatement != null) {try {preparedStatement.close();} catch (SQLException e) {e.printStackTrace();}}if (connection != null) {try {connection.close();} catch (SQLException e) {e.printStackTrace();}}
}
?下面是大致的解釋
-
try 塊:
try
塊中的代碼是你希望正常執行的代碼。在代碼中,try
塊包含建立數據庫連接、獲取用戶輸入、準備和執行SQL語句等操作。connection = dataSource.getConnection();
嘗試建立與數據庫的連接。preparedStatement = connection.prepareStatement(sql);
準備SQL語句。preparedStatement.executeUpdate();
執行SQL語句。
-
catch 塊:
catch
塊捕獲在try
塊中發生的異常。在代碼中,捕獲的異常類型是SQLException
,這是處理SQL操作時可能拋出的異常類型。catch (SQLException e)
表示捕獲SQLException
異常。e.printStackTrace();
打印異常的堆棧跟蹤信息,幫助我們了解錯誤發生的具體位置和原因。
-
finally 塊:
finally
塊中的代碼無論是否發生異常都會執行,通常用于清理資源。在你的代碼中,finally
塊用于關閉PreparedStatement
和Connection
對象,以防止資源泄漏。if (preparedStatement != null) { preparedStatement.close(); }
關閉PreparedStatement
對象。if (connection != null) { connection.close(); }
關閉Connection
對象。
使用tyr-catch-finally結構去寫,能夠捕獲到異常,也讓代碼更具"健壯性"?
展示類
展示類中,我們就能看見結果集了,本質上來說,展示就是查詢,然后打印出查詢的結果
所以代碼如下
package Operation;
import Book.BOOK;
import Book.BookList;
import com.mysql.cj.jdbc.MysqlDataSource;import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class Show implements WORK
{@Overridepublic void work(BookList bookList) throws SQLException{// 1 創建DataSource dataSource = new MysqlDataSource();((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/jsh?characterEncoding=utf8&useSSL=false");((MysqlDataSource) dataSource).setUser("root");((MysqlDataSource) dataSource).setPassword("454284665");// 2 建立鏈接Connection connection = dataSource.getConnection();// 3 創建sql語句String sql = "SELECT * FROM lib";PreparedStatement preparedStatement = connection.prepareStatement(sql);// 4 發送給服務器并獲取結果ResultSet resultSet = preparedStatement.executeQuery();// 5 處理結果while (resultSet.next()){String name = resultSet.getString("name");String author = resultSet.getString("author");int price = resultSet.getInt("price");String type = resultSet.getString("type");String state=resultSet.getString("state");System.out.println("書名: " + name + " 作者: " + author + " 價格: " + price + " 類型: " + type + " 狀態: "+state);}// 6 釋放資源resultSet.close();preparedStatement.close();connection.close();}
}
結果集中它通過一套getXXX方法來獲取數據,通過next()方法來讀取給個查詢的字段
我們通過這兩種方法獲得數據庫的數據,然后打印出來
最后釋放資源
借閱與歸還類
借閱也是先通過查詢,如果有查詢的書,就把state修改為 '已借出' 即可
package Operation;
import Book.BOOK;
import Book.BookList;
import com.mysql.cj.jdbc.MysqlDataSource;import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class Borrow implements WORK
{@Overridepublic void work(BookList bookList) throws SQLException{DataSource dataSource=new MysqlDataSource();((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/jsh?characterEncoding=utf8&useSSL=false");((MysqlDataSource)dataSource).setUser("root");((MysqlDataSource)dataSource).setPassword("454284665");//2 建立鏈接Connection connection=dataSource.getConnection();Scanner sc=new Scanner(System.in);System.out.println("請輸入你要借的書的名字");String name=sc.nextLine();//3String sql = "select * from lib where name= ?and state ='未被借出'";PreparedStatement preparedStatement = connection.prepareStatement(sql);preparedStatement.setString(1, name);// 4 發送給服務器并獲取結果ResultSet resultSet = preparedStatement.executeQuery();if(resultSet.next()){String sql1="update lib set state ='已借出' where name=?";PreparedStatement preparedStatement1=connection.prepareStatement(sql1);preparedStatement1.setString(1,name);int n= preparedStatement1.executeUpdate();if(n>0){System.out.println("借閱成功");preparedStatement1.close();}}else{System.out.println("沒有找到這本書,借閱失敗");}//5 釋放資源resultSet.close();preparedStatement.close();connection.close();
歸還和借閱正好相反,這里我同樣用try-catch-finally結構去寫
package Operation; import Book.BOOK; import Book.BookList; import com.mysql.cj.jdbc.MysqlDataSource;import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Scanner; public class Return implements WORK {@Overridepublic void work(BookList bookList) {DataSource dataSource = new MysqlDataSource();((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/jsh?characterEncoding=utf8&useSSL=false");((MysqlDataSource) dataSource).setUser("root");((MysqlDataSource) dataSource).setPassword("454284665");Connection connection = null;PreparedStatement preparedStatement = null;PreparedStatement preparedStatement1 = null;ResultSet resultSet = null;try {connection = dataSource.getConnection();Scanner sc = new Scanner(System.in);System.out.println("請輸入你要歸還的書的名字:");String name = sc.nextLine();String sql = "SELECT * FROM lib WHERE name = ? AND state = '已借出'";preparedStatement = connection.prepareStatement(sql);preparedStatement.setString(1, name);resultSet = preparedStatement.executeQuery();if (resultSet.next()) {String sql1 = "UPDATE lib SET state = '未被借出' WHERE name = ?";preparedStatement1 = connection.prepareStatement(sql1);preparedStatement1.setString(1, name);int n = preparedStatement1.executeUpdate();if (n > 0) {System.out.println("歸還成功");}} else {System.out.println("沒有找到這本書或這本書未被借出, 歸還失敗");}} catch (SQLException e) {System.out.println("數據庫操作失敗: " + e.getMessage());} finally {// 按正確順序關閉資源if (resultSet != null) {try {resultSet.close();} catch (SQLException e) {e.printStackTrace();}}if (preparedStatement != null) {try {preparedStatement.close();} catch (SQLException e) {e.printStackTrace();}}if (preparedStatement1 != null) {try {preparedStatement1.close();} catch (SQLException e) {e.printStackTrace();}}if (connection != null) {try {connection.close();} catch (SQLException e) {e.printStackTrace();}}}
?這樣我們就可以實現將數據寫入數據庫中,當然這是簡易版本的,可以擴展的內容還有很多,例如可以建一張表存儲用戶的信息,可以建表存儲已經借走的書等
就留給讀者們自己去寫了,這只是一個練習的實例
完整代碼我已經分享