Read data from oracle - Java JDBC

Java examples for JDBC:Oracle

Description

Read data from oracle

Demo Code



import java.sql.*;

public class Oracle {

  public static void main(String[] args) {
    try{//from   w w w .j a v  a  2 s  .  c o m
      Oracle oracle = new Oracle();
        String sql="select instance_name,host_name from gv$instance";
        ResultSet rs = oracle.select(sql);
        while(rs.next()){
           System.out.println(rs.getString(1)+"\t\t"+""+rs.getString(2));
        }
    }catch (Exception e){
      e.printStackTrace();;
    }
  }
  
  private Connection conn = null;
  private String url = "jdbc:oracle:thin:@172.28.1.221:1521:YourDB";
  private String driver = "oracle.jdbc.driver.OracleDriver";
  private String user = "sys as sysdba";
  private String password = "password";

  public Connection create() {
    try {
      Class.forName(driver);
      conn = DriverManager.getConnection(url, user, password);
    } catch (Exception ex) {
      System.out.println(ex);
    }
    return conn;
  }

  public ResultSet select(String sql) {
    Connection conn = create();
    ResultSet rs = null;
    try {
      Statement st = conn.createStatement();
      rs = st.executeQuery(sql);
    } catch (Exception e) {
      System.out.println(e);
    } finally{
      //conn.close();
    }
    return rs;
  }

  public void execute(String sql) {
    Connection conn = create();
    ResultSet rs = null;
    try {
      Statement st = conn.createStatement();
      st.executeUpdate(sql);
    } catch (Exception e) {
      System.out.println(e);
    }

  }
}

Related Tutorials