日期:2014-05-16  浏览次数:20545 次

Oracle数据库链接(二)

这个项目中使用的oracle数据库链接是通过实现了一个ConnDBa类来简化oracleJDBC的操作

?
ConnDBa.java
package two;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ConnDB {

  static Connection conn = null;
  static Statement sm = null;
  static ResultSet rs = null;

  public static Connection getConn() {
    try {
      Class.forName("oracle.jdbc.driver.OracleDriver");
      conn = DriverManager.getConnection(
          "jdbc:oracle:thin:@localhost:1521:orcl", "scott", "hello");
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return conn;
  }

  public static void close() {
    try {
      if (rs != null) {
        rs.close();
      }
      if (sm != null) {
        sm.close();
      }
      if (conn != null) {
        conn.close();
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}

?

在另一个类中使用这个辅助类
OracleDB.java
package two;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

class OracleDB {

  public static void main(String[] args) {

    Connection conn = null;
    Statement sm = null;
    ResultSet rs = null;
    try {
      conn = ConnDB.getConn();
      sm = conn.createStatement();
      rs = sm.executeQuery("select * from dept");
      while (rs.next()) {
        System.out.println("deptno==" + rs.getInt(1));
        System.out.println("dname==" + rs.getString(2));
        System.out.println("loc==" + rs.getString(3));
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      ConnDB.close();
    }

  }
}
?
?