1. 程式人生 > >資料庫 (JDBC增刪改查)

資料庫 (JDBC增刪改查)

                                                 開發步驟

一.匯入jar包 

 1.匯入mysql-connector-java-5.1.0-bin.jar包;

二.寫實體類:(實體層)

package com.ybb.entity;

public class Goods {
	
	private int id;
	private String name;
	private double price;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public Goods(int id, String name, double price) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
	}
	public Goods() {
		super();
		// TODO Auto-generated constructor stub
	}	

}

三.建立一個dao包(dao層)

1.寫BaseDao類(是一個封裝的類,裡面封裝的是增刪改查的核心方法,可以通過呼叫來實現)

package com.ybb.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class BaseDao {
	
	private Connection coon;
	//獲取連線資料庫
	public Connection getConnnection(){
		try {
			//通過反射載入驅動
			
			Class.forName("com.mysql.jdbc.Driver");

			//獲取連線
			coon=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/school?useUnicode=true&characterEncoding=utf8", "ybb", "1234");			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return coon;
		
	}
	
	//update users set name=? where id=?;
	//增刪改
	public int update(String sql,Object[]objects){
		int num=0;	
		try {
			//獲取連線
			coon=getConnnection();
			PreparedStatement ps=coon.prepareStatement(sql);
			if (objects!=null&&objects.length>0) {
				for (int i = 0; i < objects.length; i++) {
					//替換佔位符
					ps.setObject((i+1), objects[i]);
				}
			}

			//執行增刪改操作
			num=ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return num;		
	}
	
	//查詢
	public ResultSet getResultSet(String sql,Object[]objects){
		ResultSet rs=null;
		try {
			//獲取連線
			coon = getConnnection();
			PreparedStatement ps = coon.prepareStatement(sql);
			if (objects!=null&&objects.length>0) {
				for (int i = 0; i < objects.length; i++) {
					ps.setObject((i+1), objects[i]);
				}
			}
			//執行查詢方法
			rs=ps.executeQuery();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return rs;	
	}
   

	 //關閉資源
    public  void  close(Connection connection ,PreparedStatement ps , ResultSet  rs){
        try {
            if(connection !=null){
                connection.close();
            }

            if(ps !=null){
                ps.close();
            }

            if(rs !=null){

                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

2.寫介面類

package com.ybb.dao;

import java.util.List;

import com.ybb.entity.Goods;

public interface GoodsDao {
    
	//查詢所有
	public List<Goods> findGoods();
	
	//增加
	public int addGoods(Goods goods);
	
	
	//修改
	public int updateGoods(Goods goods);
	
	//刪除
	public int deleteGoods(int id);
	
	//分頁(pageIndex:頁數,pageSize:頁量)
	public List<Goods> fengYe(int pageIndex,int pageSize);

}

3.寫實現介面類

package com.ybb.dao;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.ybb.entity.Goods;

public class GoodsDaoImpl extends BaseDao implements GoodsDao{
 
	
	//查詢
	@Override
	public List<Goods> findGoods() {
		// TODO Auto-generated method stub
		List<Goods>lt=new ArrayList<Goods>();
		try {
			String sql = "select * from goods";
			Object[] objects = {};
			ResultSet rs = this.getResultSet(sql, objects);
			 while (rs.next()){
	                Goods goods=new Goods();
	                goods.setId(rs.getInt("id"));
	                goods.setName(rs.getString("name"));
	                goods.setPrice(rs.getDouble("price"));
                    lt.add(goods);               
	            }
		} catch (Exception e) {
			// TODO: handle exception
		}
		return lt;
	}

	@Override
	public int addGoods(Goods goods) {
		// TODO Auto-generated method stub
		int count=0;
		String sql="insert into goods(name,price) values(?,?)";
		Object[]objects={goods.getName(),goods.getPrice()};
		/*ResultSet rs=this.getResultSet(sql, objects);*/
		count=this.update(sql, objects);
		return count;
	}

	//修改
	@Override
	public int updateGoods(Goods goods) {
		// TODO Auto-generated method stub
		int count=0;
		String sql="update goods set name=?,price=? where id=?";
		Object[]objects={goods.getName(),goods.getPrice(),goods.getId()};
		count=this.update(sql, objects);		
		return count;
	}
    
	//刪除
	@Override
	public int deleteGoods(int id){
		// TODO Auto-generated method stub
		int count=0;
		String sql="delete from goods where id=?";
		Object[]objects={id};
		count=this.update(sql, objects);
		return count;
	}

	@Override
	public List<Goods> fengYe(int pageIndex, int pageSize) {
		// TODO Auto-generated method stub
		return null;
	}

}

四.測試類(測試層)

//		GoodsDaoImpl goodsDaoImpl=new GoodsDaoImpl();
//		//查詢
//		List<Goods>lt=goodsDaoImpl.findGoods();
//		for (Goods goo:lt) {
//			System.out.println(goo.getName());
//		}
		
		//增加
//		Goods goods=new Goods();
//		goods.setName("保溫杯");
//		goods.setPrice(23.5);
//		int count=goodsDaoImpl.addGoods(goods);
//		System.out.println(count);
		
		//修改
//		Goods goods=new Goods();
//		goods.setId(17);
//		goods.setName("ipad");
//		goods.setPrice(2399.0);
//		int count=goodsDaoImpl.updateGoods(goods);
//		System.out.println(count);
		
		//刪除
//		int count=goodsDaoImpl.deleteGoods(22);
//		System.out.println(count);