JDBC程序的一般步骤

直接上例子

  1 import java.sql.Connection;
  2 import java.sql.DriverManager;
  3 import java.sql.ResultSet;
  4 import java.sql.SQLException;
  5 import java.sql.Statement;
  6 
  7 
  8 
  9 /*
 10  * 编写JDBC程序的一般步骤
 11  */
 12 
 13 
 14 public class TestJDBC {
 15 
 16     /**
 17      * @param args
 18      */
 19     public static void main(String[] args){
 20         
 21         Connection conn = null;
 22         Statement stmt = null;
 23         ResultSet rs = null;
 24         
 25         //***第一步1.Load the Driver***
 26         //Class相当于一个类装载器,根据一个类的名字帮助你相关的类个实现出来
 27         try {
 28             Class.forName("oracle.jdbc.driver.OracleDriver");
 29         } catch (ClassNotFoundException e) {
 30             // TODO Auto-generated catch block
 31             e.printStackTrace();
 32         }
 33         //向DriverManager提供一个实例,则可得到与数据库相连的连接
 34         //上面的是第一种写法
 35         //第二种
 36         //new oracle.jdbc.driver.OracleDriver();
 37         
 38         
 39         //***第二步2.Connect to the DataBase***
 40         //参数1 = 数据库的连接字符串,各个数据库不同 URL
 41         //参数1 ELLENIOU SID的服务和监听必须打开
 42         //参数2 = 用户名
 43         //参数3 = 密码
 44         try {
 45             conn  = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ELLENIOU", "scott", "tiger");
 46             
 47             
 48             
 49             
 50             
 51             //***第三步3.Execute the SQL***
 52             //1.Connection.CreateStatement();
 53             //2.Statement.executeQuery();
 54             //3.Statement.executeUpdate();
 55             //查询语句
 56             stmt = conn.createStatement();
 57             //rs相当于游标
 58             rs = stmt.executeQuery("select * from dept");
 59             
 60             //***第四步4.通过循环取得结果集***
 61             while(rs.next()){
 62                 
 63             //***第五步5.对取得的结果进行处理***
 64                 System.out.println(rs.getString("deptno"));
 65                 
 66             }
 67             
 68             
 69         } catch (SQLException e) {
 70             e.printStackTrace();
 71             System.out.println(e);
 72         }finally{
 73             
 74             //***第六步6.关闭相关进程***
 75             try {
 76                 if(rs !=null){
 77                 rs.close();
 78                 rs = null;
 79                 }
 80                 if(stmt !=null){
 81                 stmt.close();
 82                 stmt = null;
 83                 }
 84                 if(conn !=null){
 85                 conn.close();
 86                 conn = null;
 87                 }
 88             } catch (SQLException e) {
 89                 e.printStackTrace();
 90             }
 91             
 92         }
 93         
 94         
 95         
 96         
 97     
 98         
 99         
100     }
101 
102 }
原文地址:https://www.cnblogs.com/elleniou/p/2638884.html