A SELECT Example


The following sample program shows how to retrieve and list all the names (first_name, last_name) from the employee_tbl2 table, which is partially defined as

1CREATE TABLE  employee_tbl2 (
2  employee_id   NUMBER(6),
3  first_name    VARCHAR2(20),
4  last_name     VARCHAR2(25)  CONSTRAINT  emp_last_name_nn  NOT NULL,
5  email         VARCHAR2(25)  CONSTRAINT  emp_email_nn      NOT NULL,
6  phone_number  VARCHAR2(20) );
7 
8ALTER TABLE  employee_tbl2  ADD (
9  CONSTRAINT  emp_emp_id_pk  PRIMARY KEY( employee_id ));

Name (args[0]) =

             
01// Import the following packages to use JDBC.
02import  java.sql.*;
03import  java.io.*;
04import  oracle.sql.*;
05import  oracle.jdbc.*;
06import  oracle.jdbc.pool.OracleDataSource;
07 
08class  Select {
09  public static void  main( String args[ ] ) throws SQLException {
10    String user     = "C##user_id";
11    String password = "password";
12    String database = "20.185.147.112:1521/xe";
13 
14    // Open an OracleDataSource and get a connection.
15    OracleDataSource ods = new OracleDataSource( );
16    ods.setURL     ( "jdbc:oracle:thin:@" + database );
17    ods.setUser    ( user );
18    ods.setPassword( password );
19    Connection conn = ods.getConnection( );
20 
21    // Create a Statement
22    Statement stmt = conn.createStatement( );
23 
24    // Select first_name, last_name, and email columns from the employee_tbl2 table
25    String  query  = "SELECT first_name, last_name, email FROM employee_tbl2";
26            query += "  WHERE last_name LIKE '%" + args[0].trim( ) + "%'";
27    System.out.println( "<font color='#3366CC'><h4>" + query + "</h4></font>" );
28    ResultSet rset = stmt.executeQuery( query );
29 
30    // Iterate through the result and print the employee names.
31    while ( rset.next( ) )
32      System.out.println (
33        rset.getString( 1 ) + " " + rset.getString( 2 ) + " 🠞 " +
34        rset.getString( 3 ) );
35 
36    // Close the RseultSet.
37    rset.close( );
38 
39    // Close the Statement.
40    stmt.close( );
41 
42    // Close the Connection.
43    conn.close( );
44  }
45}




      Why do cows wear bells?    
      Because their horns don’t work.