标签:
本例子程序是根据马士兵老师所讲+自己的注释。写的比较全面,特别是最后释放资源的代码。
1 package com.ayang.jdbc; 2 3 import java.sql.*; 4 5 public class TestJDBC { 6 7 8 public static void main(String[] args) { 9 Connection conn = null; 10 Statement stmt = null; 11 ResultSet rs = null; 12 try{ 13 //1、注册驱动 14 //new oracle.jdbc.driver.OracleDriver(); 15 Class.forName("oracle.jdbc.driver.OracleDriver"); 16 //2、建立连接 17 conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:ORCL","scott", "root"); 18 //3、创建语句 19 stmt = conn.createStatement(); 20 //4、执行语句 21 rs = stmt.executeQuery("select * from dept2"); 22 System.out.println("deptno ||dname ||location"); 23 //5、处理结果 24 while(rs.next()){ 25 System.out.println(rs.getString("deptno")+" "+rs.getString("dname")+" "+rs.getString("loc")); 26 } 27 }catch (ClassNotFoundException e) { 28 System.out.println("未正常加载jdbc驱动"); 29 e.printStackTrace(); 30 }catch(SQLException e){ 31 e.printStackTrace(); //log for java 32 33 }finally{ 34 //6、释放资源 35 try { 36 if(rs != null){ //如果rs没有初始化,这肯定报exception,故判断一下 37 rs.close(); 38 rs = null; //垃圾回收随时可以回收 39 }if(stmt != null){ 40 stmt.close(); 41 stmt = null; 42 }if(conn != null){ 43 conn.close(); 44 conn = null; 45 } 46 } catch (SQLException e) { 47 e.printStackTrace(); 48 } 49 50 51 } 52 } 53 54 }
标签:
原文地址:http://www.cnblogs.com/lihaoyang/p/4472871.html