自己封装一个工具类

封装JDBC工具类

public class JDBCUtils {
    
    
    public static DataSource dataSource;

    static {
    
    
        try {
    
    
            Properties properties = new Properties();
            properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
    
    
            throw new RuntimeException(e);
        }
    }

    //方式一:硬编码(更改起来不方便 .class文件需要编译成.java文件才能让我们看的懂才能进行相应的修改操作)
    public static Connection getConnection1() {
    
    
        Connection connection = null;
        try {
    
    
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/study_test?serverTimezone=UTC", "root", "123456");
        } catch (Exception e) {
    
    
            throw new RuntimeException(e);
        }
        return connection;
    }

    //从配置文件中读取(只需更改配置文件)
    public static Connection getConnection2() throws IOException, SQLException, ClassNotFoundException {
    
    
        Connection connection = null;
        Properties prop = new Properties();
        prop.load(JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
        String driverClassName = prop.getProperty("driverClassName");
        String url = prop.getProperty("url");
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");
        Class.forName(driverClassName);
        connection = DriverManager.getConnection(url, username, password);
        return connection;
    }

    //从连接池中获取
    public static Connection getConnection3() throws SQLException {
    
    
        Connection connection = null;
        connection = dataSource.getConnection();
        return connection;
    }
   //关闭资源
    public static void closeAll(ResultSet resultSet, Statement statement, Connection connection) {
    
    
        if (resultSet != null) {
    
    
            try {
    
    
                resultSet.close();
            } catch (SQLException e) {
    
    
                throw new RuntimeException(e);
            }
        }
        if (statement != null) {
    
    
            try {
    
    
                statement.close();
            } catch (SQLException e) {
    
    
                throw new RuntimeException(e);
            }
        }
        if (connection != null) {
    
    
            try {
    
    
                connection.close();
            } catch (SQLException e) {
    
    
                throw new RuntimeException(e);
            }
        }
    }
}

封装BaseDao

public class BaseDao<T> {
    
    
    //查询多条数据
    public List<T> getList(Class<T> clazz, String sql, Object... args) {
    
    
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        List<T> list = new ArrayList<>();
        try {
    
    
            connection = JDBCUtils.getConnection3();
            ps = connection.prepareStatement(sql);
            //循环为每一个占位符赋值
            for (int i = 0; i < args.length; i++) {
    
    
                ps.setObject(i + 1, args[i]);
            }
            resultSet = ps.executeQuery();
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            int count = resultSetMetaData.getColumnCount();
            while (resultSet.next()) {
    
    
                //利用反射来实例化对象
                T t = clazz.newInstance();
                //为属性赋值
                for (int i = 1; i <= count; i++) {
    
    
                    String columnName = resultSetMetaData.getColumnName(i);
                    //利用反射来获取本类所有属性
                    Field field = clazz.getDeclaredField(columnName);
                    //属性一般都是私有的需要使用暴力反射
                    field.setAccessible(true);
                    field.set(t, resultSet.getObject(i));
                }
                list.add(t);
            }
        } catch (Exception e) {
    
    
            throw new RuntimeException(e);
        } finally {
    
    
            JDBCUtils.closeAll(resultSet, ps, connection);
        }
        return list;
    }
   //查询单条数据
    public T getOne(Class<T> clazz, String sql, Object... args) {
    
    
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        T t = null;
        try {
    
    
            connection = JDBCUtils.getConnection3();
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
    
    
                ps.setObject(i + 1, args[i]);
            }
            resultSet = ps.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int count = metaData.getColumnCount();
            if (resultSet.next()) {
    
    
                t = clazz.newInstance();
                for (int i = 1; i <= count; i++) {
    
    
                    String columnName = metaData.getColumnName(i);
                    Field field = clazz.getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(t, resultSet.getObject(i));
                }
            }
        } catch (Exception e) {
    
    
            throw new RuntimeException(e);
        } finally {
    
    
            JDBCUtils.closeAll(resultSet, ps, connection);
        }

        return t;
    }
    //更新表数据(增删改)
    public int Update(String sql, Object... args) {
    
    
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        int result = 0;
        try {
    
    
            connection = JDBCUtils.getConnection3();
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
    
    
                ps.setObject(i + 1, args[i]);
            }
            result = ps.executeUpdate();
        } catch (SQLException e) {
    
    
            throw new RuntimeException(e);
        } finally {
    
    
            JDBCUtils.closeAll(null, ps, connection);
        }
        return result;
    }
}

测试:

public class UserDao extends BaseDao<User> {
    
    
    @Test
    public void getAll() {
    
    
        String sql = "select * from user";
        List<User> list = getList(User.class, sql);
        list.forEach(System.out::println);
    }
    @Test
    public void getOne(){
    
    
        String sql="select * from user where id=?";
        User user = getOne(User.class, sql, 2);
        System.out.println("user = " + user);
    }
    @Test
    public void Update(){
    
    
        String sql="update user set username=? where id=?";
        int i = Update(sql, "小余", 5);
        System.out.println("i = " + i);
    }

}

猜你喜欢

转载自blog.csdn.net/qq_52370789/article/details/129656254