day17 9.关闭资源与异常处理
Java程序跟任何外部设备进行连接之后,都要把连接断开,把资源释放掉。Connection是一个重量级资源,Connecton占内存,Connection的获取是比较消耗资源和内存的。finally是一定会被执行,刚才玩的JDBC代码,异常都没处理直接抛出异常了,这是不负责任的行为。
package cn.itcast.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; //对异常进行try-catch public class JdbcDemo5 { public static void main(String[] args) { Connection con = null; Statement st = null; ResultSet rs = null; try { //1.注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2.获取连接 try { con = DriverManager.getConnection("jdbc:mysql:///day17", "root", ""); //3.获取操作sql语句对象Statement st = con.createStatement(); //4.执行sql rs = st.executeQuery("select * from user"); //5.遍历结果集 while(rs.next()){ int id = rs.getInt("id"); //String id = rs.getString("id");//虽然用getString()行,但是用getInt()比较合适 String username = rs.getString("username"); String password = rs.getString("password"); String email = rs.getString("email"); System.out.println(id+" "+username+" "+password+" "+email); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //6.释放资源 try { if(rs !=null ){ rs.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if(st!=null){ st.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if(con!=null){ con.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }