• oracle_jdbc_Query


    本例子程序是根据马士兵老师所讲+自己的注释。写的比较全面,特别是最后释放资源的代码。

     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 }

    欢迎关注个人公众号一起交流学习:

  • 相关阅读:
    [ACM] hdu 1166 敌兵布阵 (线段树,单点更新)
    [ACM] poj 1182 食物链(并查集)
    [ACM] hdu 1272 小希的迷宫(并查集)
    [ACM] hdu 1198 Farm Irrigation (看图枚举+并查集)
    [ACM] 携程预赛第二场 剪刀石头布(并查集)
    [ACM] hdu 1241 Oil Deposits(DFS)
    Jerry Mouse
    [2010山东ACM省赛] Balloons(搜索)
    java作业不能运行
    sql 语句
  • 原文地址:https://www.cnblogs.com/lihaoyang/p/4472871.html
Copyright © 2020-2023  润新知