JDBC 编程工具包

工具包结构

工具包代码

BeanCountHander.java

import java.sql.ResultSet;

public class BeanCountHander implements IResultSetHandler<Integer> {
    @Override
    public Integer handle(ResultSet rs) throws Exception {
        if (rs.next()) {
            return rs.getInt("count");
        }
        return 0;
    }
}

BeanHandler.java

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.sql.ResultSet;

public class BeanHandler<T> implements IResultSetHandler<T> {
    private Class<T> classType;

    public BeanHandler(Class<T> classType) {
        this.classType = classType;
    }

    @Override
    public T handle(ResultSet rs) throws Exception {
        if (rs.next()) {
            // 创建一个对象
            T obj = this.classType.newInstance();
            // 通过内省来拿属性 , Object.class
            BeanInfo bf = Introspector.getBeanInfo(this.classType, Object.class);

            // 获取所有属性描述器
            PropertyDescriptor[] pds = bf.getPropertyDescriptors();
            // 遍历每一个属性的描述 器
            for (PropertyDescriptor pd : pds) {
                if(pd.getName().equals("anonymousName"))
                    continue;
                Object val = rs.getObject(pd.getName());
                // 给对象设置属性值
                pd.getWriteMethod().invoke(obj, val);
            }
            return obj;
        }
        return null;
    }
}

BeanListHandler.java

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class BeanListHandler<T> implements IResultSetHandler<List<T>> {

    private Class<T> classType;

    public BeanListHandler(Class<T> classType) {
        this.classType = classType;
    }

    @Override
    public List<T> handle(ResultSet rs) throws Exception {
        List<T> list = new ArrayList<>();
        while (rs.next()) {
            // 创建一个对象
            T obj = this.classType.newInstance();
            // 通过内省来拿属性
            BeanInfo bf = Introspector.getBeanInfo(this.classType, Object.class);
            // 获取所有属性描述器
            PropertyDescriptor[] pds = bf.getPropertyDescriptors();
            // 遍历每一个属性的描述 器
            for (PropertyDescriptor pd : pds) {
                if(pd.getName().equals("anonymousName"))
                    continue;
                Object val = rs.getObject(pd.getName());
                // 给对象设置属性值
                pd.getWriteMethod().invoke(obj, val);
            }
            // 把对象存放 到集合当中
            list.add(obj);
        }
        return list;
    }
}

IResultSetHandler.java

import java.sql.ResultSet;

public interface IResultSetHandler<T> {
	T handle(ResultSet rs) throws Exception;
}

DBUtil.java

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBUtil {
    static String driver;
    static String url;
    static String username;
    static String password;
    static {
        try {
            // 加载配置文件
            Properties p = new Properties();
            FileInputStream in = new FileInputStream("resource/db.properties");
            p.load(in);
            driver = p.getProperty("driver");
            url = p.getProperty("url");
            username = p.getProperty("username");
            password = p.getProperty("password");
            // 加载驱动
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        try {
            // 连接数据
            return DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 关闭连接
    public static void close(Connection conn, Statement st, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(DBUtil.getConnection());
    }
}

Template.java

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

import edu.fzu.tmall.util.hander.IResultSetHandler;

public class Template {
	public static int executeUpdate(String sql, Object... params) {
		try (Connection c = DBUtil.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
			// 遍历参数
			for (int i = 0; i < params.length; i++) {
				ps.setObject(i + 1, params[i]);
			}
			// 执行语句
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public static <T> T executeQuery(String sql, IResultSetHandler<T> rh, Object... params) {
		ResultSet rs = null;
		try (Connection c = DBUtil.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
			// 遍历参数
			for (int i = 0; i < params.length; i++) {
				ps.setObject(i + 1, params[i]);
			}
			// 执行语句
			rs = ps.executeQuery();
			return rh.handle(rs);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(null, null, rs);
		}
		return null;
	}
}

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3307/tmall?characterEncoding=UTF-8
username=root
password=abcd
posted @ 2019-03-29 14:33  Lomen~  阅读(579)  评论(0编辑  收藏  举报