Introduction to Java Library Management system (from simple to complex) (v) __java

Source: Internet
Author: User
Tags class operator redis stmt create database

Author: Alextan

E-mail:alextanbz@gmail.com


Our last blog was to use IO to implement the book Management system, but in practice, it is impossible to use IO processing, why. First of all, we have to read the code every time and write a file, the amount of data is not good, but if the amount of data.  It's too big. For example, the day before yesterday, I learned the process of Redis, with Redis-dump exported 3.7 g of JSON data, the results found that can not open this JSON file, because my Computer configuration is too weak, the data volume of the file is too large, so there is no open situation. So, if the amount of data in the back is too large, or IO to achieve, the program will crash. So next, we will change this program to use the database to implement, the database we temporarily selected is MySQL.


Environment Configuration:

Before writing code, we need to configure the environment, my MySQL is using the Phpstudy integrated Mysql,wamp can also, or other can also, anyway, only need to install MySQL on it, how to install, I am not too much elaborated here, very simple.

After installing MySQL, we need to download Java MySQL driver, download address: https://dev.mysql.com/downloads/connector/j/

After downloading, configure the tutorial this is it, simple: http://jingyan.baidu.com/article/ed15cb1b512a651be36981f4.html


Build Table:

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);

Note: Auto_increment is an added meaning (this applies to MySQL), if you are using the other database, try identity (1,1)


The configuration is good, the table is established, we begin to write code.

I'll just post the code directly.
Code:


directory structure:

Because we use the database operation, so the front of the book,booklist are removed, specific in the code reflected:

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 block E.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 block E.printstacktrace ();
		return false; } public boolean Changeboo (int id,string bookname,string changename) {try {Connection conn = Database.getcon
			Nection ();
			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 block E.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 ("Find success.")
			The result you are looking for is: \ n "); while (Rs.next ()) {//If there is data in the object, it loops out System.out.println ("No.:" +rs.getint ("id") + "title:" +rs.getstring ("bookname") + ",
			Author: "+rs.getstring (" author ") +", Prices: "+rs.getfloat (" price "));
			} rs.close ();
		Stmt.close ();
		catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace ();
			The public void Printallbook () {//3. Operation database through the database connection, to implement and delete to check try {Connection conn = database.getconnection ();
			Statement stmt = Conn.createstatement ();
			ResultSet rs = stmt.executequery ("Select Id,bookname,author,price from Book");//select Import Java.sql.ResultSet; while (Rs.next ()) {//If there is data in the object, it loops out System.out.println ("No.:" +rs.getint ("id") + "title:" +rs.getstring ("bookname") + ",
			Author: "+rs.getstring (" author ") +", Prices: "+rs.getfloat (" price "));
			} rs.close ();
		Stmt.close (); catch (SqlexCeption e) {//TODO auto-generated catch block E.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 block E.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 code block (load driver, connect database into static block)
	static{
		try {
				//1. Load Driver
				Class.forName ("Com.mysql.jdbc.Driver");
				2. Access to the database connection
				conn = drivermanager.getconnection (URL, NAME, PASSWORD);
				SYSTEM.OUT.PRINTLN ("Database connection succeeded.") ");
				} catch (ClassNotFoundException e) {
					e.printstacktrace ();
				} catch (SQLException e) {
					e.printstacktrace () ;
				}
			}
	
	Provide a way to get the database connection public
	static Connection getconnection () {return
		conn;
	}
	
	Equivalent to destructors in 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) {//read user input int choice = Scan.nextint (); if (choice = = 6) {System.out.println ("Successful exit system, welcome again.")
				");
			Break
			Switch (choice) {case 1:addbook (); Case 2:deleteboo ();
			Break Case 3:changeboo ();
			Break Case 4:findboo ();
			Break Case 5:clearboo ();
			Break DEFAULT:SYSTEM.OUT.PRINTLN ("illegal importation"); Printmenu ();
			Continue
			}/* while (TRUE) {//calling different methods based on user input 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 ("Successful exit system, welcome again.")
				");
			Break
		} */} void Printmenu () {///Print menu System.out.println ("Welcome ..."); System.out.println ("Add books...
		1 "); System.out.println ("delete book ...)
		2 "); System.out.println ("Modify the book ...)
		3 "); System.out.println ("Search for books ...")
		4 "); System.out.println ("Empty the book ...")
		5 "); System.out.println ("Exit system ...")	
	6 ");
		} void Clearboo () {Operator Operator = new Operator ();
		Boolean issuccess = Operator.clearbook (); if (issuccess) {System.out.println ("empty successful.")
		"); ' Else {System.out.println (' empty failed.
		");
		} void Addbook () {Scanner scan = new Scanner (system.in);
		System.out.println ("Please enter the name of the book:");
		String bookname = Scan.next ();
		System.out.println ("Please enter author:");
		String author = Scan.next ();
		SYSTEM.OUT.PRINTLN ("Please input Unit Price:");
		float price = Scan.nextfloat ();
		Operator Operator = new Operator ();
		Boolean issuccess = Operator.addbook (BookName, author, Price); if (issuccess) {System.out.println ("increase success.")
		"); else {System.out.println ("Increase failed.")
		");
	} operator.printallbook ();
		} void Deleteboo () {Scanner scan = new Scanner (system.in);
		String name = ""; while (true) {System.out. println ("Please enter the way to delete the book: 1, Number/2, title/3, Return to the main menu");
			int choose = Scan.nextint ();
			int id =-1;
				if (choose = = 1) {System.out.println ("Please enter the number of the book to delete:");
				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 ("Delete succeeded.")
					"); else System.out.println ("delete failed.")
					");
				Operator.printallbook (); } else {System.out.println ("input error.")
				");
				} else if (choose = 2) {System.out.println ("Please enter the title you want to delete:");
				Name = Scan.next ();
				Operator Operator = new Operator ();
					if (name!= "") {Boolean issuccess = Operator.deletebook (id,name); if (issuccess) System.out.println ("Delete succeeded.")
					"); else System.out.println ("delete failed.")
					");
				Operator.printallbook ();
				else {System.out.println ("not found the title you Want");
				} else if (choose = 3) {printmenu ();
			Break' Else {System.out.println (' input illegal.
			");
		}} void Changeboo () {Scanner scan = new Scanner (system.in);
		String name = "";
			while (true) {System.out.println ("Please enter a way to modify the book by: 1, Number/2, title/3, Return to the main menu");
			int choose = Scan.nextint ();
			int id =-1;
				if (choose = = 1) {System.out.println ("Please enter the number of the book to be modified:");
				id = scan.nextint ();
				Operator Operator = new Operator ();
					if (Id >-1) {System.out.println ("Please enter what you want to modify why the title:");
					String str = Scan.next ();
					Boolean issuccess = Operator.changeboo (id,str,name); if (issuccess) System.out.println ("modified successfully.")
					"); else System.out.println ("Modify failed.")
					
					");
				Operator.printallbook (); } else {System.out.println ("input error.")
				");
				} else if (choose = 2) {System.out.println ("Please enter the title you want to modify:");
				Name = Scan.next ();
				Operator Operator = new Operator ();
					if (name!= "") {System.out.println ("Please enter what you want to modify why the title:");
					String str = Scan.next (); Boolean IsSuccess = Operator.changeboo (id,str,name); if (issuccess) System.out.println ("modified successfully.")
					"); else System.out.println ("Modify failed.")
					");
				Operator.printallbook ();
				} else if (choose = 3) {printmenu ();
			Break ' Else {System.out.println (' input illegal.
			");
		}} void Findboo () {Scanner scan = new Scanner (system.in);
		Operator Operator = new Operator ();
		String name = "";
		int id =-1;
			while (true) {System.out.println ("Please enter the way to find the book: 1, Number/2, title/3, Return to the main menu");
			int choose = Scan.nextint ();
				if (choose = = 1) {System.out.println ("Please enter the number of the book you want to find:");
				id = scan.nextint ();
				if (Id >-1) {Operator.findboo (id,name); } else {System.out.println ("input error.")
				");
				} else if (choose = 2) {System.out.println ("Please enter the title you want to find:");
				Name = Scan.next ();
				if (name!= "") {Operator.findboo (id,name);
				} else if (choose = 3) {printmenu ();
			Break else {SysteM.out.println ("Enter illegal.
			");
	}} public static void Main (string[] args) {//TODO auto-generated method Stub new MainClass ();
 }

}

So, we use the database to achieve the library management system, with the database to achieve a great advantage is to greatly simplify the "additions and deletions" of the operation (we can also see from the code volume), at the same time hardly need to worry about the large amount of data problems.


Please look forward to the next: Java Introductory tutorial Book Management System (from simple to complex) (vi) Reproduced please specify the source: http://blog.csdn.net/alextan_/article/details/67640511


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.