JDBC: API - 释放资源

释放资源 

 

1) 需要释放的对象:ResultSet 结果集,Statement 语句,Connection 连接

2) 释放原则:先开的后关,后开的先关。ResultSet ==> Statement ==> Connection

3) 放在哪个代码块中:finally 块 

  与IO流一样,使用后的东西都需要关闭!关闭的顺序是先开后关, 先得到的后关闭,后得到的先关闭

 

 

代码示例

public class JDBCDemo05 {
        public static void main(String[] args)  {

            Connection connection = null;
            Statement statement = null;
            ResultSet resultSet = null;

             try { 
                //1.注册驱动(省略) 
                //2.获取连接
                String url = "jdbc:mysql://localhost:3306/db4";
                connection = DriverManager.getConnection(url, "root", "123456");
                //3.获取 Statement对象
                statement = connection.createStatement();

                String sql = "select * from jdbc_user";
                resultSet = statement.executeQuery(sql);  
             } catch (SQLException e) {
                     e.printStackTrace();
             } finally {
                  /** 
                     * 开启顺序: connection ==> statement => resultSet
                     * 关闭顺序: resultSet ==> statement ==> connection 
                     */
                  try { 
                            connection.close();
                            resultSet.close(); 
                            statement.close();
                  } catch (SQLException e) { 
                         e.printStackTrace();
                  }            
             }
        }
}      

 

JDBC使用的步骤总结

  1. 获取驱动(可以省略)

  2. 获取连接

  3. 获取Statement对象

  4. 处理结果集(只在查询时处理)

  5. 释放资源 

posted @ 2021-07-22 11:45  Jasper2003  阅读(76)  评论(0编辑  收藏  举报