JDBC工具类

抽取JDBC工具类:JDBCUtils

目的:简化代码

分析:

  注册驱动也抽取

  抽取一个方法获取连接对象

    需求:不想传递参数(麻烦),还得保持工具类的通用性

    解决:配置文件

      jdbc.properties

        url=

        user=

        password=

        以后想要修改连接对象的话,只需要修改配置文件里面的路径即可,不需要修改代码

  抽取一个方法释放资源

 

配置文件

 

 

JDBC工具类

复制代码
public class JDBCUtils {
    private static String url;
    private static String user;
    private static String password;
    private static String driver;
    /**
     * 文件的读取,只需要读取一次即可拿到这些值,使用静态代码块
     */
    static{
        //读取资源文件,获取值

        try {
            //1.创建Properties集合
            Properties properties = new Properties();
            //获取src路径下的文件的方式---》ClassLoader 类加载器
            ClassLoader classLoader = JDBCUtils.class.getClassLoader();
            URL resource = classLoader.getResource("jdbc.properties");
            String path = resource.getPath();
            System.out.println(path);
            //2.加载文件
            properties.load(new FileReader(path));
            //3.获取数据,赋值
            url=properties.getProperty("url");
            user=properties.getProperty("user");
            password=properties.getProperty("password");
            driver=properties.getProperty("driver");
            //4.注册驱动
            Class.forName(driver);

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 获取连接
     * @return   连接对象
     */
    public static Connection getConnection()throws SQLException{
        return DriverManager.getConnection(url,user,password);
    }

    /**
     * 释放资源
     * @param stmt
     * @param conn
     */
    public static void close(Statement stmt,Connection conn){
        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 释放资源
     * @param stmt
     * @param conn
     */
    public static void close(ResultSet re, Statement stmt, Connection conn){
        if (re!=null){
            try {
                re.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
复制代码

 

演示案例

复制代码
public class JDBCDemo8lx {
    /*
    定义一个方法,查询emp表的数据将其封装为对象,然后装载集合,返回
     */

    public static void main(String[] args) {
        List<Emp> all = new JDBCDemo8lx().findAll();
        for (Emp emp : all) {
            System.out.println(emp);
        }

    }

    public List<Emp> findAll() {
        ResultSet rs = null;
        Connection conn = null;
        Statement stat = null;
        List<Emp> list = null;
        try {
            conn = JDBCUtils.getConnection();
            // 3.定义数据库
            String sql = "select * from emp";
            // 4.获取执行sql的对象
            stat = conn.createStatement();
            // 5.执行sql
            rs = stat.executeQuery(sql);
            // 6.遍历结果集,封装对象,装载集合
            Emp emp = null;
            list = new ArrayList<Emp>();
            while (rs.next()) {
                int id = rs.getInt("id");
                String ename = rs.getString("ename");
                int job_id = rs.getInt("job_id");
                int mgr = rs.getInt("mgr");
                Date joindate = rs.getDate("joindate");
                double salary = rs.getDouble("salary");
                double bonus = rs.getDouble("bonus");
                int dept_id = rs.getInt("dept_id");

                emp = new Emp();
                emp.setId(id);
                emp.setEname(ename);
                emp.setJob_id(job_id);
                emp.setMgr(mgr);
                emp.setJoindate(joindate);
                emp.setSalary(salary);
                emp.setBonus(bonus);
                emp.setDept_id(dept_id);

                // 装载集合
                list.add(emp);

            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
           JDBCUtils.close(rs,stat,conn);
        }
        return list;
    }
复制代码

 

posted @   漁夫  阅读(81)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示