对于数据库的增删该查处理

来源:互联网 发布:程序员辛苦吗 编辑:程序博客网 时间:2024/05/01 00:25
先在src下创建一个db,properties文件:

                    driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/day14_customer  //可根据实际需求进行更改
username=root
password=root
 
工具类:在utils文件夹下创建 JabcUtils类
     
package cn.itcast.utils;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.mchange.v2.c3p0.ComboPooledDataSource;



public class JdbcUtils {

    private static ComboPooledDataSource ds = null;
    static{
        try{
            /*ds = new ComboPooledDataSource();
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/day16");
            ds.setUser("root");
            ds.setPassword("root");

            ds.setInitialPoolSize(10);
            ds.setMinPoolSize(5);
            ds.setMaxPoolSize(20);*/

            ds = new ComboPooledDataSource();

        }catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public static Connection getConnection() throws SQLException{

        return ds.getConnection();
    }

    public static void release(Connection conn,Statement st,ResultSet rs){

        if(rs!=null){
            try{
                rs.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
            rs = null;

        }
        if(st!=null){
            try{
                st.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try{
                conn.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    //替换dao中的增删改方法
    public static void update(String sql,Object params[]) throws SQLException{
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try{
            conn = getConnection();
            st = conn.prepareStatement(sql);
            for(int i=0;i<params.length;i++){
                st.setObject(i+1, params[i]);
            }
            st.executeUpdate();

        }finally{
            release(conn, st, rs);
        }
    }

    //替换所有dao中的查询   策略模式
    public static Object query(String sql,Object params[],ResultSetHandler rsh) throws SQLException{

        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try{
            conn = getConnection();
            st = conn.prepareStatement(sql);
            for(int i=0;i<params.length;i++){
                st.setObject(i+1, params[i]);
            }
            rs = st.executeQuery();
            return rsh.handler(rs);

        }finally{
            release(conn, st, rs);
        }
    }
}
  
Dao增删改查,得到分页数据

package cn.itcast.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.itcast.domain.Customer;
import cn.itcast.exception.DaoException;
import cn.itcast.utils.BeanHandler;
import cn.itcast.utils.BeanListHandler;
import cn.itcast.utils.IntegerHandler;
import cn.itcast.utils.JdbcUtils;

public class CustomerDaoImpl {

    public void add(Customer c){
        try{
            String sql = "insert into customer(id,name,gender,birthday,cellphone,email,preference,type,description) values(?,?,?,?,?,?,?,?,?)";
            Object params[] = {c.getId(),c.getName(),c.getGender(),c.getBirthday(),c.getCellphone(),c.getEmail(),c.getPreference(),c.getType(),c.getDescription()};
            JdbcUtils.update(sql, params);
        }catch (Exception e) {
             throw new DaoException(e);
        }
    }

    public void update(Customer c){
        try{
        String sql = "update customer set name=?,gender=?,birthday=?,cellphone=?,email=?,preference=?,type=?,description=? where id=?";
        Object params[] = {c.getName(),c.getGender(),c.getBirthday(),c.getCellphone(),c.getEmail(),c.getPreference(),c.getType(),c.getDescription(),c.getId()};   
        JdbcUtils.update(sql, params);
        }catch (Exception e) {
             throw new DaoException(e);
        }
    }

    public void delete(String id){
        try{
            String sql = "delete from customer where id=?";
            Object params[] ={id};
            JdbcUtils.update(sql, params);
        }catch (Exception e) {
             throw new DaoException(e);
        }
    }

    public Customer find(String id){

        try{
            String sql = "select * from customer where id=?";
            Object params[] ={id};
            return (Customer) JdbcUtils.query(sql, params, new BeanHandler(Customer.class));
        }catch (Exception e) {
             throw new DaoException(e);
        }
    }


    //获取分页数据
    public List<Customer> getPageData(int startindex,int pagesize){
        try{
            String sql = "select * from customer limit ?,?";
            Object params[] = {startindex,pagesize};
            return (List<Customer>) JdbcUtils.query(sql, params, new BeanListHandler(Customer.class));
        }catch (Exception e) {
             throw new DaoException(e);
        }
    }

    //得到总记录数
    public int getTotalrecord(){
        try{
            String sql = "select count(*) from customer";
            Object params[] = {};
            long l =  (Long) JdbcUtils.query(sql,params,new IntegerHandler());
            return (int)l;
        }catch (Exception e) {
             throw new DaoException(e);
        }   
    }

}
0 0
原创粉丝点击