Java入门教程之图书管理系统(由简入繁)(五)

作者:AlexTan

E-mail: [email protected]


我们上一篇博客是用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)


配置好,表建立好后,我们就开始编写代码了。

我就直接贴代码了。

代码:


目录结构:

Java入门教程之图书管理系统(由简入繁)(五)_第1张图片

由于我们用的数据库操作,所以前面的book,booklist都去掉了,具体在代码中体现:

Java入门教程之图书管理系统(由简入繁)(五)_第2张图片

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.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 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("查找成功!您查找的结果为:\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 block
			e.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 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{
		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("删除成功!");
					else
						System.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("删除成功!");
					else
						System.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("修改成功!");
					else
						System.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("修改成功!");
					else
						System.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 stub
		new MainClass();
	}

}

那么,这样我们就用数据库实现了图书管理系统,用数据库实现的一个很大的优点就是极大的简化了“增删改查”的操作(大家从代码量也能看出来),同时几乎也不用担心数据量过大的问题了。


请期待下一篇:Java入门教程之图书管理系统(由简入繁)(六)

转载请注明出处:http://blog.csdn.net/alextan_/article/details/67640511


你可能感兴趣的:(Java)