将jdbc操作进行封装

本文介绍了如何通过创建JDBCUtils工具类来封装数据库操作的常见步骤,如注册驱动、获取连接和释放资源,从而避免重复代码,提高代码复用性和易用性。示例展示了如何在实际应用中调用此类进行数据库的插入操作,并在完成后正确关闭资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们知道封装的意义处理降低耦合 还有就是可以将重复的代码变成一个可以随时调用的方法 减少代码量 而我们的jdbc操作就有许多重复的代码时每次都需要写的

如:

  1. 注册驱动
  2. 获得连接
  3. 释放资源

我们发现除了获取数据库操作对象执行sql语句外 我们所有的操作都是 一成不变的 所以为了方便我们使用 我们将那些重复的操作可以写在一个指定的类中 在我们操作数据库时直接调用该类中对应的方法即可

示例:

public class jdbc_utils {
    static String url;
    static String user;
    static String pwd;
//注册驱动
    static {//因为写在静态代码块里 所以在调用该类时就会自动执行代码块中的内容
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src\\mysql.properties"));
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            pwd = properties.getProperty("pwd");
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
//与数据库进行连接
    public Connection getConnection(){
        try {
            return DriverManager.getConnection(url,user,pwd);
        } catch (SQLException e) {
           throw new RuntimeException(e);
        }
    };
//关闭连接
//因为我们有可能用不上所有对象 所以我们只需要关闭使用的对象即可
//resultSet对象就是如此 我们只有执行查询操作的时候才会用到他    
    public void close(Connection connection, ResultSet resultSet, Statement statement){
        try {
            if (connection!=null){
                connection.close();
            }
            if (resultSet!=null){
                resultSet.close();
            }
            if (statement!=null){
                statement.close();
            }
        } catch (SQLException e) {
          throw  new RuntimeException(e);
        }
    }
}

而之后我们只需要在执行 注册驱动 ,获得连接, 释放资源 时调用该类中指定的方法即可:

public class jdbc_utils_DML {
    public static void main(String[] args) throws SQLException {
        String sql="insert into admin values(1,tom)";
        //获得与数据库的连接
        Connection connection = new jdbc_utils().getConnection();
        //获取数据库操作对象
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //执行sql语句
        preparedStatement.executeUpdate();
        //释放资源
        new jdbc_utils().close(connection,null,preparedStatement);
    }
}

这样jdbc操作就会变得更加方便 重复的代码不再需要重复写

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值