商苑面馆:Java命令行版之 FoodDao层(MySQL实现)

来自CloudWiki
跳转至: 导航搜索

Dao层

Java8-1.png

前期准备

建立Food类

在entity包下建立Food类:

(如果已创建,请忽略)

package entity;

public class Food {
	//成员变量
	//名称
	private String name;
	//价格
	private double price;
	//数量
	private int num;
	
	/*构造方法*/
	public Food(){
		
	}
	public Food(String name,double price,int num){
		this.name = name;
		this.price = price;
		this.num = num;
	}
	
	//成员方法
	public String getName(){
		return this.name;
	}
	public double getPrice(){
		return this.price;
	}
	public int getNum(){
		return this.num;
	}
	//写方法
	public boolean setName(String s){
		this.name = s;
		return true;
	}
	public boolean setPrice(double p){
	    this.price = p;
	    return true;
	}
	public boolean setNum(int n){
	    this.num = n;
	    return true;
	}
	   
	public String toString(){
	    return "名称:" +this.name+"价格:"+
	               this.price + "剩余数量: " + this.num;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Food [] f = new Food[3];
		f[0] =  new Noodle("炸酱面",12,3,"不辣");
		f[1] =  new Rice("牛肉盖浇饭",3,2,"盖浇饭");
		f[2] = new SmallEat("鹌鹑蛋",3,2,"微辣");
		
		
		for(int i =0;i<f.length;i++){
			System.out.println(f[i].toString());
		}
		

	}
	public void buy() {
		// TODO Auto-generated method stub
		
	}

}

创建测试数据

(如果已创建,请忽略)

接下来我们在 cloud 数据库中创建 food数据表,表结构如下:

mysql> use cloud;
Database changed
mysql>  CREATE TABLE IF NOT EXISTS `food`(
   `id` INT UNSIGNED AUTO_INCREMENT,
   `name` VARCHAR(100) NOT NULL,
   `price` DOUBLE ,
   `num` INT ,
   PRIMARY KEY ( `id` )  
)ENGINE=InnoDB DEFAULT CHARSET=utf8;


插入一些数据:

mysql> INSERT INTO `food` (name,price,num) VALUES ('zhajiangmian',10,3);
Query OK, 1 row affected (0.12 sec)

mysql> INSERT INTO `food` (name,price,num) VALUES ('daoxiaomian',12,5);
Query OK, 1 row affected (0.04 sec)

</nowiki>

实现步骤

建立接口FoodDao

在包dao下建立抽象接口FoodDao

package dao;

import entity.Food;

public interface FoodDao {
	public boolean addFoods(Food goods);//增加商品
	  
	public Food search(String s);
	public String toString(); 
	
	
}

建立接口的实现类

接口实现类可以用多种方式实现,ArrayList,LinkedList, MySQL等

这里我们用MySQL实现

接口实现类FoodDaoSQL

package dao;
import java.sql.*;
import java.util.*;

//import entity.*;
import entity.Food;
import entity.Noodle;
public class FoodDaoSQL {
    //private Food[] n;//食物数组
	Connection con=null;
    
    public FoodDaoSQL( ){    	
    		con = getConn();
   }
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub		
		
	}

}

编写连接方法getConn

这个方法的作用主要是进行数据库的初始连接:

private static Connection getConn() {
    	// JDBC 驱动名及数据库 URL
       final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
       final String DB_URL = "jdbc:mysql://localhost:3306/cloud?characterEncoding=utf8";
     
        // 数据库的用户名与密码,需要根据自己的设置
       final String USER = "root";
       final String PASS = "000000";
       
    	Connection conn = null;       
        try {
            Class.forName(JDBC_DRIVER); //classLoader,加载对应驱动
            conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("MySQL连接成功!");
        } catch (ClassNotFoundException e) {
        	System.out.println(e.getMessage());
        } catch (SQLException e) {
        	System.out.println(e.getMessage());
        }
        return conn;
        
    }


添加商品方法:addFood( )

模仿UserDaoSQL中的addUser可以得到:

public int addFood(Food food){
		Connection conn =  this.con;//建立数据库的连接
        int i = 0; //建立一个空的整形变量i
       
        try {
            //1.创建PreparedStatement 对象,让它与一条SQL模板绑定;
             String sql = "insert into food (name,price,num) values(?,?,?)";
             PreparedStatement pstmt = (PreparedStatement) conn.prepareStatement(sql);

            //使用2. setXXX()系列方法为sql命令设置值
            pstmt.setString(1, food.getName());
            pstmt.setDouble(2, food.getPrice());  //pstmt.setInt(2, user.getAge()); pstmt.setDate  
            pstmt.setInt(3, food.getNum());
            
             //3.执行查询          
            i = pstmt.executeUpdate();
            if(i!=0){    	    
            	System.out.println(food.getName()+"插入成功!");
	        }else{
                System.out.println(food.getName()+"插入失败!");
            }
            pstmt.close();
            
        } catch (SQLException e) {//检测/捕获异常
        	System.out.println(e.getMessage());
        }
        return i;
	}

在FoodDaoSQL类的main方法中编写测试代码:

public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		
		FoodDaoSQL foodset =new FoodDaoSQL();
		Food f2 = new Food("saozimian",13,4);
		foodset.addFood(f2);//插入数据
		foodset.con.close();//关闭数据库
	}

运行、测试。

搜索食物方法:search()

模仿UserDaoSQL中的search()可以得到:

public Food search(String s){
//代码自己仿照着UserDaoSQL中的search()写即可
}

在FoodDaoSQL类的main方法中编写测试代码,测试一下

列出全部记录:toString()

模仿UserDaoSQL中的toString()可以得到:

public String toString(){
//代码自己仿照着UserDaoSQL中的toString()写即可
}

在FoodDaoSQL类的main方法中编写测试代码,测试一下

实现接口

到现在为止,UserDaoSQL已经实现了UserDao接口的全部方法,

因此可以在UserDaoSQL类名后面,加上implements UserDaob标识,表明把UserDao这个接口实现了。