Java 中封装JDBC连接到JDBCUtils工具类的详解

博主前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住也分享一下给大家,
👉点击跳转到网站

前言

在JDBC操作中,获取连接和释放资源是经常使用到的,可以将其封装成到一个工具类JDBCUtils中

JDBCUtils中有两个方法得到连接和关闭连接,代码如下

//这是一个工具类,完成mysql的连接和关闭资源
public class JDBCUtils {
    //定义相关的属性(4),因为只需要一份,因此我们做成static
    private static String user;//用户名
    private static String password;//密码
    private static String url; //url
    private static String driver;//驱动名


    //初始化相关属性值,放到静态代码块中完成
    static {
        try {
            Properties properties = new Properties();
            properties.load(new FileInputStream("src\\mysql.properties"));
            //读取相关的属性值
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            url = properties.getProperty("url");
            driver = properties.getProperty("driver");
        } catch (IOException e) {
            //在实际开发中,我们可以这样处理
            //1.将编译异常转成,运行异常
            //2.这时调用者,可以选择捕获该异常,也可以选择默认处理该异常,比较方便
            throw new RuntimeException(e);
        }
    }

    //连接方法,返回Connection
    public static Connection getConnection() {
        try {
            Class.forName(driver);
            return DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            //1.将编译异常转成,运行异常
            //2.这时调用者,可以选择捕获该异常,也可以选择默认处理该异常,比较方便
            throw new RuntimeException(e);
        }
    }

    //关闭相关资源
    /*
        1.resultSet 结果集
        2.prepareStatement 或者 Statement
        3.connection
        4.如果需要关闭资源,就传入对象,否则传入null
     */
    public static void close(ResultSet set, Statement statement, Connection connection) {
        try {
            //判断是否为null
            if (set != null) {
                set.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            //将编译异常,转换为运行异常抛出
            throw new RuntimeException(e);
        }
    }
}

JDBCUtils工具类的使用如下

public class JDBCUtils_Use {

    //使用JDBCUtils 进行DML操作(insert update delete)
    @Test
    public void testDML() {
        //1.得到连接
        Connection connection = null;

        //2.组织一个sql
        //更新记录
//        String sql = "UPDATE actor SET NAME=? WHERE id=?";

        //删除记录
        String sql = "DELETE FROM actor WHERE id=?";

        //添加记录
//        String sql = "INSERT INTO actor VALUES(?,?,?,?,?)";

        PreparedStatement preparedStatement = null;
        //创建PrepareStatement对象
        try {
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            //添加记录
//            preparedStatement.setInt(1, 3);
//            preparedStatement.setString(2, "周润发");
//            preparedStatement.setString(3, "男");
//            preparedStatement.setString(4, "1999-01-10");
//            preparedStatement.setString(5, "1234567890");

            //修改记录
//            preparedStatement.setString(1, "周星驰");
//            preparedStatement.setInt(2, 1);

            //删除记录
            preparedStatement.setInt(1, 1);
            int rows = preparedStatement.executeUpdate();
            System.out.println(rows > 0 ? "执行成功" : "执行失败");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            JDBCUtils.close(null, preparedStatement, connection);
        }
    }

    @Test
    public void testSelect() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //1.得到连接
            connection = JDBCUtils.getConnection();
            String sql = "SELECT id,name,borndate FROM ACTOR WHERE id = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, 2);
            //执行得到结果集
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                String name = resultSet.getString("name");
                int id = resultSet.getInt("id");
                Date borndate = resultSet.getDate("borndate");
                System.out.println(id + "\t" + name + "\t" + borndate);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(resultSet, preparedStatement, connection);
        }
    }
}

输出结果分别为

执行成功
2	王宝强	1980-01-03
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路宇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值