作者:AlexTan
E-mail: alextanbz@gmail.com
我們上一篇部落格是用IO來實現圖書管理系統的,但在實際情況下,用IO處理來實現是不可能的,為什麼呢。 首先,上一篇的代碼我們每運行一次都得讀一次和寫入一檔案,資料量少還行,但如果資料量很多呢。太大呢。 就比如前天我學習redis的過程中,用redis-dump匯出了3.7個G的json資料,結果發現根本無法開啟這個json檔案,原因是我電腦配置太弱,檔案的資料量又太大,所以出現了根本打不開的情況。所以,如果後面資料量過大,還是用IO來實現的話,程式是會崩潰的。因此接下來,我們將把這個程式改成用資料庫來實現,資料庫我們暫時選用的是mysql。
環境配置:
在編寫代碼之前,大家需要配置一下環境,我的mysql是用的phpStudy整合的mysql,wamp也可以,或者其他的也可以,反正只需要裝上mysql就可以了,怎麼裝,我這裡就不過多闡述了,很簡單的。
裝好mysql後,我們需要下載java的mysql驅動,下載地址:https://dev.mysql.com/downloads/connector/j/
下載後,配置教程就這個吧,簡單一點的:http://jingyan.baidu.com/article/ed15cb1b512a651be36981f4.html
建表:
create database books;use books;create table book(id int(6) primary key not null auto_increment,bookname varchar(255),author varchar(255),price float);
注意: auto_increment是自增的意思(這個適用於mysql),如果你用的其他資料庫,試試 identity(1,1)
配置好,表建立好後,我們就開始編寫代碼了。
我就直接貼代碼了。
代碼:
目錄結構:
由於我們用的資料庫操作,所以前面的book,booklist都去掉了,具體在代碼中體現:
Operator.java:
package control;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import jdbc.database;public class Operator {public boolean addBook(String bookname,String author,float price){try {Connection conn = database.getConnection();Statement stmt = conn.createStatement();String sql = "insert into book(bookname,author,price) values('"+bookname+"','"+author+"',"+price+")";//System.out.println(sql);stmt.execute(sql);stmt.close();return true;} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();return false;}}public boolean deleteBook(int id,String bookname){try {Connection conn = database.getConnection();Statement stmt = conn.createStatement();String sql;if(id != -1){sql = "delete from book where id ="+id;}else{sql = "delete from book where bookname ='"+bookname+"'";}stmt.execute(sql);stmt.close();return true;} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();return false;}}public boolean changeBoo(int id,String bookname,String changename){try {Connection conn = database.getConnection();Statement stmt = conn.createStatement();String sql;if (id != -1){sql = "update book set bookname='"+changename+"'"+" where id="+id;}else{sql = "update book set bookname='"+changename+"'"+" where bookname='"+bookname+"'";}stmt.execute(sql);stmt.close();return true;} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();return false;}}public void findBoo(int id,String bookname){try {Connection conn = database.getConnection();Statement stmt = conn.createStatement();String sql;if (id != -1){sql = "select id,bookname,author,price from book"+" where id="+id;System.out.println(sql);}else{sql = "select id,bookname,author,price from book"+" where bookname='"+bookname+"'";}ResultSet rs = stmt.executeQuery(sql);System.out.println("尋找成功。您尋找的結果為:\n");while(rs.next()){//如果對象中有資料,就會迴圈列印出來System.out.println("編號:"+rs.getInt("id")+" 書名:"+rs.getString("bookname")+",作者:"+rs.getString("author")+",價格:"+rs.getFloat("price"));}rs.close();stmt.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void printAllbook(){//3.通過資料庫的串連操作資料庫,實現增刪改查try {Connection conn = database.getConnection();Statement stmt = conn.createStatement();ResultSet rs = stmt.executeQuery("select id,bookname,author,price from book");//選擇import java.sql.ResultSet;while(rs.next()){//如果對象中有資料,就會迴圈列印出來System.out.println("編號:"+rs.getInt("id")+" 書名:"+rs.getString("bookname")+",作者:"+rs.getString("author")+",價格:"+rs.getFloat("price"));}rs.close();stmt.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public boolean clearBook(){try {Connection conn = database.getConnection();Statement stmt = conn.createStatement();String sql = "truncate table book";stmt.execute(sql);stmt.close();return true;} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();return false;}}}
database.py:
package jdbc;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class database {private static final String URL="jdbc:mysql://localhost:3306/books";private static final String NAME="root";private static final String PASSWORD="root";private static Connection conn=null;//靜態代碼塊(將載入驅動、串連資料庫放入靜態塊中)static{try {//1.載入驅動程式Class.forName("com.mysql.jdbc.Driver");//2.獲得資料庫的串連conn = DriverManager.getConnection(URL, NAME, PASSWORD);System.out.println("資料庫連接成功。");} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}}//對外提供一個方法來擷取資料庫連接public static Connection getConnection(){return conn;}//相當於c++中的解構函式protected void finalize() throws java.lang.Throwable{conn.close();}}
MainClass.java:
package ui;import java.util.Scanner;import control.Operator;public class MainClass {public MainClass(){Scanner scan = new Scanner(System.in);printMenu();while(true){//讀取使用者輸入int choice = scan.nextInt();if(choice == 6){System.out.println("成功退出系統,歡迎再次光臨。");break;}switch(choice){case 1: addBook(); break;case 2: deleteBoo(); break;case 3: changeBoo(); break;case 4: findBoo(); break;case 5: clearBoo(); break;default: System.out.println("輸入非法"); printMenu(); continue;}}/*while(true){//根據使用者輸入調用不同方法if(choice == 1){addBook();}else if(choice == 2){deleteBoo();}else if(choice == 3){changeBoo();}else if(choice == 4){findBoo();}else if(choice == 5){System.out.println("成功退出系統,歡迎再次光臨。");break;}}*/}void printMenu(){//列印菜單System.out.println("歡迎...");System.out.println("增加圖書...1");System.out.println("刪除圖書...2");System.out.println("修改圖書...3");System.out.println("查詢圖書...4");System.out.println("清空圖書...5");System.out.println("退出系統...6");}void clearBoo(){Operator operator = new Operator();boolean isSuccess = operator.clearBook();if(isSuccess){System.out.println("清空成功。");}else{System.out.println("清空失敗。");}}void addBook(){Scanner scan = new Scanner(System.in);System.out.println("請輸入圖書名:");String bookname = scan.next();System.out.println("請輸入作者:");String author = scan.next();System.out.println("請輸入單價:");float price = scan.nextFloat();Operator operator = new Operator();boolean isSuccess = operator.addBook(bookname, author, price);if(isSuccess){System.out.println("增加成功。");}else{System.out.println("增加失敗。");}operator.printAllbook();}void deleteBoo(){Scanner scan = new Scanner(System.in);String name = "";while(true){System.out.println("請輸入按哪種方法刪除圖書:1、編號/2、書名/3、返回主菜單");int choose = scan.nextInt();int id = -1;if(choose == 1){System.out.println("請輸入要刪除的書的編號:");id = scan.nextInt();Operator operator = new Operator();//System.out.println(id);if(id > -1){boolean isSuccess = operator.deleteBook(id,name);if(isSuccess)System.out.println("刪除成功。");elseSystem.out.println("刪除失敗。");operator.printAllbook();}else{System.out.println("輸入錯誤。");}}else if(choose == 2){System.out.println("請輸入您要刪除的書名:");name = scan.next();Operator operator = new Operator();if(name != ""){boolean isSuccess = operator.deleteBook(id,name);if(isSuccess)System.out.println("刪除成功。");elseSystem.out.println("刪除失敗。");operator.printAllbook();}else{System.out.println("未尋找到您想要的書名");}}else if(choose == 3){printMenu();break;}else{System.out.println("輸入非法。");}}}void changeBoo(){Scanner scan = new Scanner(System.in);String name = "";while(true){System.out.println("請輸入按哪種方法修改圖書:1、編號/2、書名/3、返回主菜單");int choose = scan.nextInt();int id = -1;if(choose == 1){System.out.println("請輸入要修改的書的編號:");id = scan.nextInt();Operator operator = new Operator();if(id > -1){System.out.println("請輸入你要修改為什麼書名:");String str = scan.next();boolean isSuccess = operator.changeBoo(id,str,name);if(isSuccess)System.out.println("修改成功。");elseSystem.out.println("修改失敗。");operator.printAllbook();}else{System.out.println("輸入錯誤。");}}else if(choose == 2){System.out.println("請輸入您要修改的書名:");name = scan.next();Operator operator = new Operator();if(name != ""){System.out.println("請輸入你要修改為什麼書名:");String str = scan.next();boolean isSuccess = operator.changeBoo(id,str,name);if(isSuccess)System.out.println("修改成功。");elseSystem.out.println("修改失敗。");operator.printAllbook();}}else if(choose == 3){printMenu();break;}else{System.out.println("輸入非法。");}}}void findBoo(){Scanner scan = new Scanner(System.in);Operator operator = new Operator();String name = "";int id = -1;while(true){System.out.println("請輸入按哪種方法尋找圖書:1、編號/2、書名/3、返回主菜單");int choose = scan.nextInt();if(choose == 1){System.out.println("請輸入要尋找的書的編號:");id = scan.nextInt();if(id > -1){operator.findBoo(id,name);}else{System.out.println("輸入錯誤。");}}else if(choose == 2){System.out.println("請輸入您要尋找的書名:");name = scan.next();if(name != ""){operator.findBoo(id,name);}}else if(choose == 3){printMenu();break;}else{System.out.println("輸入非法。");}}}public static void main(String[] args) {// TODO Auto-generated method stubnew MainClass();}}
那麼,這樣我們就用資料庫實現了圖書管理系統,用資料庫實現的一個很大的優點就是極大的簡化了“增刪改查”的操作(大家從代碼量也能看出來),同時幾乎也不用擔心資料量過大的問題了。
請期待下一篇:Java入門教程之圖書管理系統(由簡入繁)(六) 轉載請註明出處:http://blog.csdn.net/alextan_/article/details/67640511