A Dynamic Database Access

A dynamic database access is you do not know at compile time whether you will be issuing queries or updates.
The following code shows a generic database program that blindly receives an SQL command to execute from the Web.

SQL> CREATE TABLE employee_tbl3 (
  2    employee_id   NUMBER(6), 
  3    first_name    VARCHAR2(20),
  4    last_name     VARCHAR2(25) CONSTRAINT emp_last_name_nn3 NOT NULL,
  5    email         VARCHAR2(25) CONSTRAINT emp_email_nn3     NOT NULL,
  6    phone_number  VARCHAR2(20) ) ;

SQL> ALTER TABLE employee_tbl3 ADD (
  2    CONSTRAINT emp_emp_id_pk3 PRIMARY KEY( employee_id ) );

SQL (p1.txt) =

             
// Import the following packages to use JDBC.
import  java.sql.*;
import  java.io.*;
import  oracle.sql.*;
import  oracle.jdbc.*;
import  oracle.jdbc.pool.OracleDataSource;

class   DynamicSQL {
  public static void  main( String args[ ] ) throws SQLException {
    String user     = "C##user.id";
    String password = "password";
    String database = "65.52.222.73:1521/cdb1";

    // Open an OracleDataSource and get a connection.
    OracleDataSource ods = new OracleDataSource( );
    ods.setURL     ( "jdbc:oracle:thin:@" + database );
    ods.setUser    ( user );
    ods.setPassword( password );
    Connection conn = ods.getConnection( );

    try {
      // The parameter, sql, is too long as an argument.
      // Read the parameter, sql, written to the file p1.txt.
      FileInputStream    stream     = new FileInputStream  ( "p1.txt" );
      InputStreamReader  iStrReader = new InputStreamReader( stream );
      BufferedReader     reader     = new BufferedReader   ( iStrReader );
      String  sql = reader.readLine( );
      if ( sql == null )  sql = "";
      else  sql = sql.trim( );
 
      try {
        Statement  stmt = conn.createStatement( );
        System.out.print( "" + sql + "" );
        if ( stmt.execute( sql ) ) {
          ResultSet          results = stmt.getResultSet( );
          ResultSetMetaData  meta    = results.getMetaData( );
          int  cols = meta.getColumnCount( );
          while ( results.next( ) )
            for ( int i = 1;  i <= cols;  i++ ) {
              Object  ob = results.getObject( i );
              System.out.print( meta.getColumnLabel( i ) + " ➜ " + ob.toString( ) );
            }
          results.close( );
        } 
        stmt.close( );      
      }
      catch ( SQLException ex ) { System.out.println( ex ); } 
    }
    catch ( IOException ex ) { System.out.println( ex ); } 
    conn.close( );
  }
}

Few comments about the above program:


      What’s the difference between a well dressed man on a bike and    
      a poorly dressed man on a unicycle?    
      Attire.