Header image  
Oracle VI  
line decor
  HOME :: BUSINESS :: COMPUTING :: LIFESTYLE :: PASTIME ::SCIENCES ::
line decor
   
 oracle VI
 
       
CONNECT TO A DELPHY SYSTEM

1 Setup the environment

If you are running a C Shell, add the following lines in the .cshrc file in your home directory:

setenv ORACLE_HOME /cs/oracle8i
setenv ORACLE_SID oracle1
setenv LD_LIBRARY_PATH ${LD_LIBRARY_PATH}:${ORACLE_HOME}/lib
#if you don't have LD_LIBRARY_PATH originally, use the following
#setenv LD_LIBRARY_PATH ${ORACLE_HOME}/lib

#also some for JDBC program
set path=(/fs/opt/jdk1.2.2/bin $path $ORACLE_HOME/bin)
setenv CLASSPATH .:${ORACLE_HOME}/jdbc/lib/classes12.zip

For Bash, add the following lines in the .bashrc file in your home directory:

export ORACLE_HOME=/cs/oracle8i
export ORACLE_SID=oracle1
export LD_LIBRARY_PATH=$(LD_LIBRARY_PATH):$(ORACLE_HOME)/lib
#if you don't have LD_LIBRARY_PATH originally, use the following
#export LD_LIBRARY_PATH=$(ORACLE_HOME)/lib

#also some for JDBC program
export PATH=/fs/opt/jdk1.2.2/bin:$PATH:$(ORACLE_HOME)/bin
export CLASSPATH=.:$(ORACLE_HOME)/jdbc/lib/classes12.zip

After change the shell file, run:

source .cshrc
or
source .bashrc

to activate the setting.

1.2 Connect the database

1) Start the SQLPLUS

sqlplus /nolog

2) Connect to Oracle database

sqlplus> connect userid/password@'(description=(address=(protocol=tcp)(host=delphi.cs.ucsb.edu)(port=1521))(connect_data=(service_name=oracle1.cs.ucsb.edu)))';

3) Now you can play on the database after you see the connection successful message.

1.3 A sample JDBC program

Here is a sample Java program illustrating the usage of JDBC (thin). You can use it as the start point of your project.

Chapter 2 TA's Guide

This chapter is about the user management for TA's usage. To execute the commands in this chapter, you need the dba privilege. In our case, first ask the department support (support@cs.ucsb.edu) to grant you the access of dba account for Oracle on delphi.cs.ucsb.edu, which is "oracle", and ask me for the password of dba account in Oracle, which is "SYSTEM" or "SYS". Follow the below steps to log in as dba:
1. Login as "oracle" on delphi.cs.ucsb.edu
2. Run "sqlplus" and input "SYSTEM/password" or "SYS/password".

2.1 Create users

To create the Oracle users for students, execute the following command:

sqlplus> CREATE USER username
IDENTIFIED BY password
DEFAULT TABLESPACE users
TEMPORARY TABLESPACE temp
QUOTA 50M ON users;
sqlplus> GRANT connect TO username;

Note that here the italic word means the things you need to input. And don't forget the ";" at the end of the command. Actually you can put the commands in a file and execute the file in SQLPLUS. Here is the sample file for creating a user. Execute the file by

sqlplus> start addorauser.ora

2.2 Alter users

You can change the properties of a user account through "ALTER USER" command. For example if you want to change the password of user James, do as follows:

sqlplus> ALTER USER James
IDENTIFIED BY newpassword;

2.3 Drop users

You need to use "DROP USER" to drop all the schema objects associating with a user account.

sqlplus> DROP USER James CASCADE;

Chapter 3 Other Administrations

This chapter is for the use of my own including restart the database, etc.

1) Restart the database

a. Start the listener: by "lsnrctl" or "netca"

b. Start up the database:

sqlplus /nolog
sqlplus> connect SYSTEM/password as sysdba;
sqlplus> startup;

 

 


SPANISH - CREACION Y MANIPULACION DE TABLAS



La creación y manipulación de tablas 

Tipos de datos en SQL

Operadores y condiciones lógicas

La sentencia CREATE TABLE

Estructura general

Uso simplificado

Manejo de restricciones de integridad

La sentencia ALTER TABLE

La sentencia  DROP TABLE

 
 

VARCHAR2(size):

     (varchar)

Cadena de caracteres de longitud variable (max 4000, min 1). Hay que especificar el tamaño

CHAR(size) 

Tipos de datos en SQL 

NUMBER(p,s)

Numero con precisión p (max 38, min 1) y escala s (max 127, min -84)

precisión: número de dígitos

escala: número de cifras decimales

 
 

Tipos de datos en SQL 

LONG 

Cadena de caracteres de longitud variable de hasta 2 gigabytes

LONG RAW(size)

Cadena de datos binarios de longitud variable hasta 2 gigabytes. Hay que especificar el tamaño 

DATE

Tipo fecha

RAW(size)

Cadena de datos binarios de longitud variable hasta 2000 bytes. Hay que especificar el tamaño

 
 

Operadores en SQL 

Resumen de operadores

 
 

Comparadores Especiales 

Comparador IS NULL

Detecta valores nulos (MAY BE SELECT)

(A=10), A is null false,  A is not null true

A = (<>) Null desconocido

Comparador BETWEEN

Detecta valores entre dos constantes

between x and y >= x and <=y

Comparador IN

Detecta pertenencia a conjunto

a in (1,2,3) true si a=1 o a=2 o a=3

 
 

Comparadores Especiales 

Comparador LIKE

Sirve para utilizar mascaras en cadenas de caracteres

- sustituye cualquier carácter

% sustituye cualquier cadena 

Ejemplos:

x LIKE -A-- true si x=1A23                                  false si x=1A234

x LIKE %A% true si x=1AX%                                       true si X=ABLA

 
 

La sentencia CREATE TABLE  

CREATE TABLE [usuario.]nombre_tabla

   ({datos_columna | restricciones de tabla}

   [,{datos_columna | restricciones de tabla}]...)  
 
 
 
 

La parte no sombreada corresponde cuestiones avanzadas

Nivel físico

Control de transacciones

Creación de tablas derivadas 

    

[PCTFREE n], [PCTUSED n], [INITRANS n ], [MAXTRAN n] [TABLESPACE nombre],

[STORAGE nombre]

[ CLUSTER nombre_cluster(columna[,columna]...)]

[AS consulta] 

 
 

La sentencia Create Table 

datos_columna:

              nombre tipo_de dato [DEFAULT expresion]   

           [restriccion_de _columna]

El tipo de dato se da entre los permitidos

Se pueden dar valores por defecto distintos del nulo

Se pueden restringir las columnas individualmente

     (Análisis  posterior)

El nombre de columna es el del atributo

 
 

La sentencia Create Table 

Restricciones asociadas a tablas:

[CONSTRAINT nombre]

[{UNIQUE | PRIMARY KEY} (columna[,columna]...)]

[CONSTRAINT nombre]

[FOREING KEY (columna[,columna]...) REFERENCES [usuario.]nombre_tabla  [(columna[,columna]...)]

[CONSTRAINT nombre]

[CHECK (condicion_con_varios_campos)]

 
 

La sentencia Create Table 

Restricciones asociadas a tablas:

Las condiciones se almacenan en el catálogo, para reconocerlas fácilmente es bueno darles nombre

UNIQUE : no se repiten valores en tuplas distintas

PRIMARY KEY: las columnas implicadas forman la llave primaria  (UNIQUE +NOT NULL)

FOREING KEY: las columnas implicadas forman llave exterior a la llave primaria de la tabla REFERENCES.

    Si se especifican campos imponemos una condición de inclusión de dominio

CHECK permite condiciones lógicas entre campos

 
 

La sentencia Create Table 

Restricciones asociadas a  las columnas:

[[CONSTRAINT nombre] NOT NULL]

[[CONSTRAINT nombre] {UNIQUE | PRIMARY KEY}]

[[CONSTRAINT nombre]  REFERENCES [usuario.]nombre_tabla [(columna)]]

[[CONSTRAINT nombre] CHECK (condicion)]

Tienen el mismo sentido anterior

NOT NULL: el campo no admite valores nulos. 

 
 

La sentencia Create Table 

Ejemplo 1:

     create table alumnos (dni varchar(8) constraint al1 primary key,

                   ape1 varchar(10) not null,

                   ape2 varchar(10) not null ,

                   nombre varchar(10) not null ,

                     edad number(3)

                   constraint al2 check   (edad between 17 and 90) ,

                     provincia varchar(10),

                     beca char(2) constraint al3 check (beca in ('si','no')),

                     sexo char(1) constraint al4 check  (sexo in ('v','m')))

    Crea una tabla de alumnos con restricciones asociadas a columnas, describe llave primaria, condiciones de no nulo y restricciones de dominio.

 
 

La sentencia Create Table 

Ejemplo 2:

     create table asigna (asi# varchar(4) primary key ,

               nombreas varchar(30) not null,

               curriculum varchar(20) not null ,

               credt number(4,1) not null ,

        credpr number(4,1) not null,

                 caracter char(2) check (caracter in ('tr','ob','op','lc')),

                temp char(2) check (temp in ('cu','an')),

              check ((temp='cu' and credt+credpr between 4.5 and 9)

                     or (temp='an' and credt+credpr between 6 and 12)))  

Crea una tabla de asignaturas con restricciones asociadas a columnas y a tabla

 
 

La sentencia Create Table 

Ejemplo 3:

create table matricula(codas varchar(4) references asigna,

codal varchar(8) references alumnos,

curso varchar(9) not null,

calificacion char(2) (check calificacion in ('np','su','ap','no','sb','mh')),

primary key (codas,codal,curso))

Crea una tabla de asignaturas con restricciones asociadas a columnas  y a tabla . Establece llaves exteriores

 
 

La sentencia Alter Table 

Formato general

ALTER TABLE [usuario].table

       [ADD ({datos_columna | restricciones de tabla}

       [{datos_columna | restricciones de tabla} ...) ]

      [MODIFY (datos_columna [,datos_columna]  ...)]

      [DROP CONSTRAINT restriccion]

      [PCTFREE n], [PCTUSED n], [INITRANS n ], [MAXTRAN n]  

      [TABLESPACE nombre],  [STORAGE nombre]

      [BACKUP]

     

 
 

La sentencia Alter Table 

Ejemplos:

alter table alumnos add (origen char(2)

check (origen in (‘cu’,’lo’,’fp’,’es’,’ot’),

media number(2,2)) 

alter table alumnos modify (nombre null)

alter table alumnos drop constraint al3

alter table alumnos add ( constraint al3

        check (edad between 18 and 80))

Cuando se modifica una columna solo se puede alterar la restricción de no null

Para alterar otras restricciones hay que borrarlas y volverlas a añadir   
 
 
 
 

 
 

La sentencia DROP TABLE 

Formato general

     DROP TABLE [usuario.]tabla

Borra la tabla y su contenido. Borra índices asociados a ella. Deja inválidos vista y sinónimos

    Solo puede borrar una tabla su propietario o el DBA

 

 

"ORA-01555: Snapshot too old: rollback...too small". Why do I get it? How can I stop it?

despite we have a 6 GB tablespace for rollback segments and
the maximum size for a rollback segment output for hwmsize is only from v$rollstat,we are sometimes getting ora-1555 errors.so nobody says that our rollback segment tablespace size isnt enough! .then why we are getting this error?

some init parameters:
transactions=9011
transaction_per_rollback_segment=8
number of rollback segments=30
each rollback segment has the following storage parameters:

(INITIAL 10240K NEXT 10240K OPTIMAL 20480K   MINEXTENTS 2 MAXEXTENTS 505)

(note: we are using Baan ERP,and have an average of 150 concurrent users,each user open avarage of 5 sessions)

Thanks in advance.

 

1) My editorial comment: The error results from an architectural problem with the Oracle database itself that has existed since Oracle’s very beginning of rollback segments. The fact that it occurs at all is, in my opinion, an Oracle BUG, which Oracle refuses to fix, so you and I must implement our own workarounds to deal with this problem. To compound the problem, the “fix” that we infer from the error message (in your case, to “increase the size of rollback segment number 4 named R03”) is virtually useless in resolving the problem. To COMMIT “early and often” as we typically hear, may not be a viable option. So, I shall explain the PROBLEM and some SOLUTIONS in the following.

2) Background and a scenario to understanding the error:
Let’s assume the following:
Assumption 1: a database with seven rollback segments.

Assumption 2: One of rollback segments, R07, our DBA has made extremely large, and we do as you suggest, 'set transaction use rollback segment R07' before our long-running transaction.

Assumption 3: the other six rollback segments are of ‘normal’ size (whatever ‘normal’ is).

Scenario:
At 12:02:35, User A executes an update transaction that Oracle assigns to rollback segment R01, starting its writing at R01’s Block Number 126 of 128, since User Z is using blocks 1-125.

At 12:02:39, User Z commits her changes (freeing up blocks 1-125 of rollback segment R01).

At 12:02:40, User B begins our large, long-running transaction. As we designed, Oracle assigns this transaction to R07 (the way big rollback segment). This large transaction needs to see database data that was “true” (i.e., committed) at the beginning of this transaction. User A changed database blocks that User B will read later at, say 12:23:30; Oracle copied User A’s original data blocks (that were “true” at 12:02:40) to rollback segment R01. The only place on earth that User B will be able to find data that was “true”/committed at the start of User B transaction (at 12:02:40) is in rollback segment R01.

At 12:02:45, User A commits her changes. Her pre-change, consistent, PRE-COMMIT images occupied blocks 126, 127, 128, 1, 2, and 3 of rollback segment R01.

At 12:02:50 through 12:03:20, Users C, D, E, F, G, and H initiate transactions that Oracle automatically assigns to rollback segments R02, R03, R04, R05, R06, and R07, respectively.

At 12:03:30, User J initiates a transaction. Oracle’s “round-robin”-rollback-segment-assignment algorithm goes back to R01. To determine how to use rollback segment R01 (i.e., where to begin writing rollback data), Oracle asks the question, “Are there any un-committed transactions in rollback segment R01, whose rollback data we still need FOR THE TRANSACTION THAT WROTE THE DATA?” The answer is “No”, (since COMMIT happened at 12:02:45) therefore Oracle begins writing rollback data to R01’s first available location, Block Number 1. Notice, then, that User J’s rollback data overwrites User A’s rollback images, WHICH User B NEEDS TO READ IN 20 MINUTES FROM NOW !!!

At 12:23:30, User B reaches the point where she needs to read the data that was true when User B’s transaction began at 12:02:40. The only place that data resided was in blocks 126, 127, 128, 1, 2, and 3 of rollback segment R01. Those data a LONG GONE, having been overwritten by at least User J’s rollback entries. Oracle generates the error: “ORA-01555: snapshot too old…” Notice also, that the gigantic rollback segment R07 didn’t help us at all since the data we needed was in one of the ‘normal’ sized rollback segments.

Possible solutions:
Solution 1: Make ALL rollback segments GIGANTIC. How large is GIGANTIC? So large that during the life of your longest-running transaction, the OTHER concurrently running transactions could not possibly generate enough rollback entries to “rollover” on itself and overwrite rollback entries from other previously committed/rolledback transactions, which still-running, long-running transactions still need. The problem here is, who has a crystal ball to anticipate just how large each rollback segment must be to ensure no rollover. Even if we could anticipate how gigantic ALL rollback segments must be, think of all the space that the rollback segments would NOT be using 99% of the time. What an (expensive) waste of disk space.

Solution 2: Kick everyone else off your Oracle instance while your long-running transaction executes. Yea, right !!! I know what kind mutiny that would cause at our company.

Solution 3: (This is the solution our organization uses to inoculate against ORA-01555 and we have found it to never fail us.) Before running a known long-running transaction, we create a bogus transaction (such as “INSERT INTO DUMMY VALUES (‘X’);) for each on-line rollback segment in the database (except the SYSTEM rollback segment, which an application transaction would never use.) We do a “SET TRANSACTION USE ROLLBACK SEGMENT <rollback segment name>;” for each of the transactions. These bogus transactions, since they remain ‘active’ during the life of your long-running transaction, prevent Oracle from rolling over a rollback segment on itself; thus preventing the loss of vital rollback data to the long-running, referencing transaction. Instead of rolling over upon themselves, the rollback segments ‘grow’ by adding more extents rather than re-using still-needed extent blocks. For this to work, each of the bogus transactions needs to originate from a different session/window. Once your long-running transaction successfully runs to its natural end (including COMMIT), then you can rollback each of the bogus transactions.

If each of your rollback segments have a ‘…STORAGE (OPTIMAL xxMB)…”, then each rollback segment will shrink down to the OPTIMAL size, thus freeing up all of the “extra” space that the bogus transactions caused in order to preserve the vital rollback entries.

IMPORTANT NOTE: Following the completion of your long-running transaction, you MUST close off each of the bogus transactions with either an explicit or implicit COMMIT or ROLLBACK. If you do not stop the bogus transactions, then they cause the rollback segments to grow until you are out of disk space.


 

JAVA ORACLE EXAMPLE:

/*
 * @author  Reghu
 * @version 1.2
 *
 * Development Environment        :  JDeveloper 2.0
 * Name of the Application        :  DMLSample.java
 * Creation/Modification History  :
 *
 *    Reghu       27-Dec-1998      Created
 *    Sujatha     21-May-2002      Certified on Oracle9i JDeveloper
 *    Savitha     10-Jan-2003      Certified on Linux
 *                                 Included checkTables() method
 *
 */
package oracle.otnsamples.jdbc.dml;

// Package for JDBC classes
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.ResultSet;

// Package for AWT classes
import java.awt.Dimension;
import java.awt.Toolkit;

// Java utility classes
import java.util.Enumeration;
import java.util.Properties;
import java.util.ResourceBundle;
import java.io.IOException;

// oracle jdbc classes
import oracle.jdbc.pool.OracleDataSource;

/**
 * This application illustrates the SQL DML operations like SELECT, INSERT,
 * UPDATE and DELETE from a java program using JDBC. The user can insert,select,
 * update and delete records from the otn_airlines table using this sample.
 *
 * The GUI for this sample is handled in DMLFrame.java
 *
 *The sample uses the JDBC-Thin driver.
 *
 */
public class DMLSample {

  /** Database Connection Object */
 
  private Connection connection = null;

  /** GUI handler for this sample */
  private DMLFrame gui;

  /**
   *  Constructor , instantiates GUI.
   */
  public DMLSample() {
    gui = new DMLFrame(this); // Instantiate GUI
 
    // Display the frame in the center of screen
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize  = gui.getSize();
    if( frameSize.height > screenSize.height ) {
      frameSize.height = screenSize.height;
    }
    if (frameSize.width > screenSize.width) {
      frameSize.width = screenSize.width;
    }
    gui.setLocation((screenSize.width - frameSize.width) / 2,
                      (screenSize.height - frameSize.height) / 2);
    gui.setVisible(true);
  }

  /**
   *  Main entry point for the class. Instantiates the DMLSample class
   *  and sets up the database connection.
   */
  public static void main( String args[] ) {
    DMLSample dml = new DMLSample();  // Instantiate DMLSample class
    //create connection object
    dml.connection = dml.dbConnection();

    // check if connection exists, else create it
    if( dml.connection != null ) {
      // Check if 'otn_airlines' table is present, else create it
      dml.checkTables();
    }
  }

  /**
   *  Dispatches the GUI events to the appropriate method, which performs
   *  the required JDBC operations. This method is invoked when event occurs
   *  in the GUI (like table Selection, Button clicks, etc.). This method
   *  is invoked from the setupListeners method of DMLFrame.java
   */
  public void dispatchEvent (String eventName) {

    // Get the user input values for code, name and partner
    String code = gui.codeTextfield.getText();
    String name = gui.nameTextfield.getText();
    String partner = gui.partnerTextfield.getText();

    // Dispatch Event
    if( eventName.equals("SELECT") )
      selectRecords( code, name, partner );
    else if( eventName.equals("UPDATE") )
      updateRecord( code, name, partner );
    else if( eventName.equals("INSERT") )
      insertRecord( code, name, partner );
    else if( eventName.equals("DELETE") )
      deleteRecord( code );
    else if( eventName.equals("EXIT") )
      exitApplication();
  }

  /**
   * This method reads Connection.properties file which is passed as
   * the parameter to it and load it into a java Properties
   * object and returns it.
   */
  private Properties loadParams(String file) throws IOException {

    // Loads a ResourceBundle and creates Properties from it
    Properties prop = new Properties();
    ResourceBundle bundle = ResourceBundle.getBundle(file);
    Enumeration enum = bundle.getKeys();
    String key = null;
    while(enum.hasMoreElements()) {
      key = (String)enum.nextElement();
      prop.put(key, bundle.getObject(key));
    }
    return prop;
  }

 /**
   * Creates a database connection object using DataSource object. Please
   * substitute the database connection parameters with appropriate values in
   * Connection.properties file
   */
  private Connection dbConnection() {
    try {
      gui.putStatus("Trying to connect to the Database");

      // Load the properties file to get the connection information
      Properties prop = loadParams("Connection");

      // Create a OracleDataSource instance
      OracleDataSource ods = new OracleDataSource();

      // Sets the driver type
      ods.setDriverType("thin");

      // Sets the database server name
      ods.setServerName((String)prop.get("HostName"));

      // Sets the database name
      ods.setDatabaseName((String)prop.get("SID"));

      // Sets the port number
      ods.setPortNumber(new Integer((String)prop.get("Port")).intValue());

      // Sets the user name
      ods.setUser((String)prop.get("UserName"));

      // Sets the password
      ods.setPassword((String)prop.get("Password"));
      connection=ods.getConnection();
      gui.putStatus("Connected to " + prop.get("SID") +
                    " Database as " + prop.get("UserName")+". Please click on SELECT"+
                    " button to view records");

    } catch(SQLException ex) { // Trap SQL errors
        gui.putStatus("Error in Connecting to the Database "+'\n'+ex.toString());
    } catch(IOException ex) { // Trap IO errors
        gui.putStatus("Error in reading the properties file "+'\n'+ex.toString());
    }
    return connection;
  }

  /**
   * Checks if the table ('otn_airlines') is present, else creates it.
   * Look into PopulateTable.java for more details
   */
  private void checkTables()   {
    Statement stmt = null;
    ResultSet rset = null;
    try     {
      stmt = connection.createStatement();

      // check from User_tables data dictionary table if the table is existing.
      rset = stmt.executeQuery(" SELECT Table_Name FROM User_Tables "+
                               " WHERE Table_Name = 'OTN_AIRLINES' ");

      // if the resultset of the above query does not have any record, it means
      // table is not existing. So the table is created.
      if (!rset.next()) {
        // call the class to create the table
        PopulateTable pop = new PopulateTable(connection, gui);
        pop.createSchemaTables();
        gui.putStatus( "otn_airlines Table created." +". Please click on SELECT"+
                    " button to view records");
      }
    } catch (SQLException sqlEx) {
       gui.putStatus(" Could not create table otn_airlines : "+sqlEx.toString());
    } finally  {
        try {
          if( rset != null ) rset.close( );
          if( stmt != null ) stmt.close( );
        } catch(SQLException ex) { }
    }
  }

  /**
   *  Method to insert a new row into the database using JDBC.
   */
  private void insertRecord( String code,String name,String partner ) {
    try {
      // Prepare a SQL statement to insert a new record into the otn_airlines table
      PreparedStatement pst = connection.prepareStatement(
                                       "INSERT INTO otn_airlines VALUES (?,?,?)");

      // Bind the column values into the PreparedStatement
      pst.setString(1, code);
      pst.setString(2, name);
      pst.setString(3, partner);

      // Execute the PreparedStatement
      pst.execute();

      // Close the PreparedStatement object
      pst.close();

      // Update GUI to reflect new record
      gui.addToJTable( code, name, partner);
      gui.putStatus("The Record is inserted");
    } catch (SQLException ex) { //Trap SQL errors
        gui.putStatus("Error in inserting record to the database " +ex.toString());
    }
  }

  /**
   *  Method to select records from the otn_airlines table using JDBC, based on the
   *  query conditions entered by the user
   */
 
  private void selectRecords(String code,String name, String partner) {
    // The SQL query for selecting the rows from the otn_airlines table
    String query = "SELECT * FROM otn_airlines "
                  + "WHERE UPPER(code) LIKE UPPER(?) AND UPPER(name) LIKE UPPER(?) "+
                  " AND UPPER(partner) LIKE UPPER(?)";
    try {
      // Create a PreparedStatement based on the query
      PreparedStatement pst = connection.prepareStatement( query );

      // Use wild card % to query all records if no query condition was entered.
      code    = "%"+code+"%";
      name    = "%"+name+"%";
      partner = "%"+partner+"%";

      // Bind the PreparedStatement with corresponding values
      pst.setString(1, code);
      pst.setString(2, name);
      pst.setString(3, partner);

      // Execute the PreparedStatement
      ResultSet resultSet = pst.executeQuery();

      gui.tmodel.clearTable(); //Clear JTable in GUI
 
      // Populating the Result set, retrieve rows, and update GUI to
      // reflect each selected record
      while (resultSet.next()) { // Point result set to next row
        // Retrieve column values for this row
        String codeVal    = resultSet.getString(1);
        String nameVal    = resultSet.getString(2);
        String partnerVal = resultSet.getString(3);
        gui.addToJTable( codeVal, nameVal, partnerVal ); // Update Jtable
      }

       // Close PreparedStatement object
       pst.close();

       gui.putStatus(gui.tmodel.getRowCount() +" Records selected");
    } catch( SQLException ex ) { //Trap SQL errors
       gui.putStatus("Error in selecting from the database " +ex.toString());
    }
  }

  /**
   *  Method to update the selected row with new values using JDBC
   */
  private void updateRecord(String code, String name, String partner) {
    try {
      //Prepare a SQL statement to update the selected record
      PreparedStatement pst = connection.prepareStatement(
                  "UPDATE otn_airlines SET name = ?, partner = ? WHERE code = ?");

      // Bind the values for the update statement
      pst.setString(1, name);    // Sets the value of name
      pst.setString(2, partner); // Sets value of partner
      pst.setString(3, code);    // Sets the value of code
      // Execute the PreparedStatement and get the number of rows updated
      int numb = pst.executeUpdate();

      // Close the PreparedStatement object
      pst.close();

      // Update the GUI to reflect the changed record
      if( numb > 0 ) {
        gui.updateJTable( code, name, partner);
        gui.putStatus( numb + "  Record updated ");
      } else
      gui.putStatus("Record not updated. Code cannot be changed.");
    } catch( SQLException ex ) {  //Trap the SQL errors
        gui.putStatus("Error in updating to the database"+ '\n'+ex.toString());
    }
  }

  /**
   *  Method to delete the selected row from the JTable
   */
  private void deleteRecord(String code) {
    try {
      // Prepare a SQL statement to delete the selected row
      PreparedStatement pst = connection.prepareStatement(
                                        " DELETE FROM otn_airlines WHERE code=?");

      // Bind the airline code to the SQL statement
      pst.setString(1, code);//sets the value of code
      // Execute the PreparedStatement and obtain the number of rows deleted
      int numb =  pst.executeUpdate();

      // Close the PreparedStatement
      pst.close();

      // Delete the row from the JTable
      if( numb > 0 ) {
        gui.deleteFromJTable();
        gui.putStatus( numb + " Record deleted" );
      } else
        gui.putStatus( "Record not deleted" );
    } catch( Exception ex ) {  //Trap the SQL errors
        gui.putStatus("Error in deleting the row "+'\n'+ex.toString());
    }
  }

  /**
   *  Close the database Connection and exit the application
   */
  private void exitApplication() {
    try {
      gui.putStatus("Closing the connection....please wait.....");
      if( connection != null )
        connection.close(); //Close the connection object.
    } catch( SQLException ex ) { //Trap SQL Errors
      gui.putStatus(ex.toString());
    }
    System.exit(0); //Exit the application
  }
}