手写JdbcUtils

目前正在学jdbc,手写了JdbcUtils,也是消除了之前学java无法很好封装jdbc的遗憾。
框架整体思路

  1. 将易变的连接数据库配置与java代码分离
  2. 将sql语句java代码分离

目前只做了selectAll和selectOne,其他也很类似。获取bean类对象,并获取其所有成员变量名才是关键。
最复杂一步是将成员变量名和数据库表字段对应起来。

/**
 * <p> Jdbc工具类
 * @version 1.0
 */
public class JdbcUtils {
    private static String driver;
    private static String username;
    private static String password;
    private static String url;
    private static Connection conn=null;
    private static Statement stmt=null;
    private static ResultSet rs=null;
    private static PreparedStatement ps=null;
    private static Class<?> clazz;
    private static Field[] fieldArray;

    static {
        // 1.初始化参数
        initProperties();
        // 2.注册驱动
        registerDriver();
        //3.初始化连接
        initConnection();
        //4.初始化操作数据库对象
        initStatement();
    }


    private JdbcUtils() {
    }

    /**
     * 指定需要的类
     *
     * @param clazz
     * @return JdbUtils对象
     */
    public static JdbcUtils getInstace(Class<?> clazz){
        JdbcUtils.clazz=clazz;
        JdbcUtils.fieldArray = clazz.getDeclaredFields();
        return new JdbcUtils();
    }


    /**
     * 初始化参数
     */
    private static void initProperties() {
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        url = bundle.getString("url");
        driver = bundle.getString("driver");
        username = bundle.getString("username");
        password = bundle.getString("password");



    }

    /**
     * 获取数据库连接
     */
    private static void initConnection() {
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 注册驱动
     */
    private static void registerDriver() {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 初始化操作数据库的对象
     */
    private static void initStatement() {
        try {
            stmt = conn.createStatement();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 初始化PreparedStatement对象
     *
     * @return
     */
    private static PreparedStatement initPrepareStatement(String sql) {
        try {
            ps = conn.prepareStatement(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return ps;
    }


    /**
     * 执行sql语句查询所有对象
     * @return 结果
     */
    public static <E> List<E> selectAll(String sql) {
        Object o = null;
        List<E> list;
        try {
            o = clazz.getConstructor().newInstance();

            list = new ArrayList<>();
            // rs = this.stmt.executeQuery(sql);
            // 使用preparedstatement防止sql注入
            ps=JdbcUtils.initPrepareStatement(sql);
            rs=ps.executeQuery();
            while (rs.next()) {
                for (Field field : fieldArray) {
                    field.setAccessible(true);
                    field.set(o, rs.getObject(field.getName()));

                }
                list.add((E) o);

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return list;


    }

    /**
     *
     * @param sql sql语句
     * @param args 参数列表
     * @return 对象
     */
    public Object selectOne(String sql,List<String> args){

        Object object=null;

        try {
            ps=JdbcUtils.initPrepareStatement(sql);
            for (int i = 0; i < args.size(); i++) {
                ps.setString(i+1,args.get(i));
            }
            rs=ps.executeQuery();
            object= clazz.getConstructor().newInstance();
            if(rs.next()){
                for (Field field : fieldArray) {
                    field.setAccessible(true);
                    field.set(object, rs.getObject(field.getName()));
                }
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        return object;
    }

    @Override
    public String toString() {
        return "JdbcUtils{" +
                "driver='" + driver + '\'' +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", url='" + url + '\'' +
                '}';
    }

    /**
     * 释放所有资源
     *  1.连接
     *  2.sql语句执行对象
     *  3.结果集对象
     */
    public void close() {

        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if(rs!=null){
                rs.close();
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if(ps!=null){
                ps.close();

            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }

    public static void main(String[] args) {

        String sql = "select * from user";
        JdbcUtils ju = JdbcUtils.getInstace(User.class);
        List<User> users = ju.selectAll(sql);
        System.out.println(users);
        sql = "select * from user where id=?";
        User user = (User) ju.selectOne(sql, Arrays.asList("1"));
        System.out.println(user);

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值