标签:finally span cat test 释放 内存 null public c代码
public class pr { public static void main(String[] args) { Connection conn = null; Statement st = null; ResultSet rs = null; try { // 加载驱动 // DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver()); 不用这种方法加载,因为源码里面已经有static代码块加载驱动了,直接加载类进内存就行了 Class.forName("com.mysql.cj.jdbc.Driver"); // 连接到数据库 conn = DriverManager.getConnection("jdbc:mysql://localhost/meiduo_mall","root","480916"); // 创建Statement对象 st = conn.createStatement(); // 执行查询,得到结果集 String sql = "select * from tb_goods_category"; rs = st.executeQuery(sql); // 遍历查询每一条数据 while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println(id + "---" + name); } } catch (Exception e) { e.printStackTrace(); } finally { // 释放资源 JDBCutils.release(conn,st,rs); // 单独写一个工具类来释放资源 } } }
工具类:
public class JDBCutils { public static void release(Connection conn,Statement st,ResultSet rs){ closeConn(conn); closeSt(st); closeRs(rs); } private static void closeRs(ResultSet rs){ try { if (rs != null){ rs.close(); } } catch (SQLException e) { e.printStackTrace(); } finally { rs = null; } } public static void closeSt(Statement st){ try { if (st != null){ st.close(); } } catch (SQLException e) { e.printStackTrace(); } finally { st = null; } } public static void closeConn(Connection conn){ try { if (conn != null){ conn.close(); } } catch (SQLException e) { e.printStackTrace(); } finally { conn = null; } } }
标签:finally span cat test 释放 内存 null public c代码
原文地址:https://www.cnblogs.com/chichung/p/10301117.html