Saturday, 14 March 2015

JDBC

http://www.localhost:8080/apex


Class.forName()

Class.forName() is used to load the specified class into the JVM's memory

class Cone {
       static {
              System.out.println("Cone is loaded");
       }
}
If class is inside the package we have to specify the full package name to class
public class LoadingClass {
       public static void main(String[] args) throws ClassNotFoundException {
              Class.forName("com.ibm.utils.Cone");
       }
}
--> Whenever  "class.forname" is executed JVM checks for specified class into the current specified location.  JVM find that class it load that class into the memory
--> Class.forname always loads the class into the JVM's memory, when class contains default constructor.
public class LoadingClass {

       public static void main(String[] args) throws ClassNotFoundException {
              Class.forName("com.ibm.utils.Ctwo");
       }

}

class Ctwo {
       static {
              System.out.println("Ctwo is loaded");
       }
      
       public Ctwo(int a) {
              System.out.println("Object is created");
       }
}
--> We can create object by calling newInstance method.
public class LoadingClass {

       @SuppressWarnings({ "rawtypes", "unused" })
       public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
              Class c = Class.forName("com.ibm.utils.Ctwo");
              Object o = c.newInstance();
       }

}

class Ctwo {
       static {
              System.out.println("Ctwo is loaded");
       }
      
       public Ctwo() {
              System.out.println("Object is created");
       }
}

Hard coding

--> Initializing values in the java code is called as hard coding.
package com.ibm.utils;

public class Cone {
       public static void main(String... args) {
              String name ="chandra";
              System.out.println("My Name is " + name);
       }
}
--> In the above code we have added name in the java code
We can resolve the problem by using
·         by passing value in the args parameters
·         by adding values in the system properties
1) public class Cone {
       public static void main(String... args) {
              if (args.length > 0) {
                     System.out.println("My Name is " + args[0]);
              }
       }
  }
C:\Users\Chandrahasa\Desktop\Java>javac Cone.java
C:\Users\Chandrahasa\Desktop\Java>java Cone Chandra
My Name is Chandra
2)
 public class Cone {
       public static void main(String... args) {
              System.out.println("My Name is " + System.getProperty("name"));
       }
}
C:\Users\Chandrahasa\Desktop\Java>javac Cone.java
C:\Users\Chandrahasa\Desktop\Java>java -Dname=chandra Cone
My Name is chandra

--> System.getProperty() always return the String value.
--> If we declare system variable and we are accessing that value without any value then we get null value.

JDBC

·         Sun Micro System has released JDBC API if a java program wants communicate with any database server.
·         In this API we have two packages
1.       Java.sql
2.       Javax.sql
·         The followings are the important interfaces as part of java.sql package
1.       Driver
2.       Connection
3.       Statement
4.       PreparedSatement
5.       CallableStatement
6.       ResultSet
7.       DataBaseMetaData
8.       ResultSetMetaData
·         The most important classes as part of java.sql package
1.       DriverManager
2.       Types
·         As part of javax.sql package most important interface is "DataSource"
·        Once SMS has released the JDBC API so many people provided implementation of this API. These implementation is called "driver"
·        By using sql*plus we can communicate with database but we can't expect user every time should expect sql queries. If we user jdbc we can create sql queries and in UI user interact with database server
·        If we want to develop JDBC program we need port number, IP address of server, service name of database system.  If we use database in locale IP address is 127.0.0.1 or localhost. Oracle default service name is XE. Port number is 152.
Procedure to create java application which communicate with database:
1.       Register driver class
2.       Create connection object
3.       Create the statement object
4.       Execute query
5.       Close connection
The following is a java program which can load the driver class
public class RegisterDriver
{
       public static void main(String[] args) throws SQLException
       {
              DriverManager.registerDriver(new OracleDriver());
              System.out.println("Driver Class is registered");
       }

}
To run the above program we need to set the ojdbc.jar file to the class path
Req: develop a java program which can establish the connection with database?
public class EstablishConnection
{
       public static void main(String[] args) throws SQLException,   ClassNotFoundException
       {
              Class.forName(ConnectionPropertiesOracle.DRIVER_CLASS);
              System.out.println("driver is registered");
              Connection con =            DriverManager.getConnection(ConnectionPropertiesOracle.URL,ConnectionProper        tiesOracle.USER_NAME,ConnectionPropertiesOracle.PASSWORD);
              System.out.println(con);
       }
}
Req: develop a java program which can create the statement Object?
public class MyStatementObject
{

       public static void main(String[] args) throws ClassNotFoundException, SQLException
       {
              Class.forName(ConnectionPropertiesOracle.DRIVER_CLASS);
              System.out.println("Driver is registered");
              Connection con = DriverManager.getConnection(ConnectionPropertiesOracle.URL,ConnectionPropertiesOracle.USER_NAME,ConnectionPropertiesOracle.PASSWORD);
              System.out.println("Connection Object="+con);
              Statement stmt = con.createStatement();
              System.out.println("Statement Object="+stmt);
       }

}
·        In JDBC we have two types of queries
1.       Select query
2.       Non select query
·        A query which is having select statement we can say that the query is select query
·        A query which doesn't have select statement then we can call it as a non select query
·        To execute select query we use executeQuery(). For non select queqy we use executeUpdate()
Req: develop a java program which can insert record into emp table?
public class InsertEmployeeData
{

       public static void main(String[] args) throws ClassNotFoundException, SQLException
       {
              Class.forName(ConnectionPropertiesOracle.DRIVER_CLASS);
              System.out.println("Driver is registered");
              Connection con = DriverManager.getConnection(ConnectionPropertiesOracle.URL, ConnectionPropertiesOracle.USER_NAME,
                      ConnectionPropertiesOracle.PASSWORD);
              System.out.println("Connection Object:" + con);
              Statement stmt = con.createStatement();
              System.out.println("Statement Object:" + stmt);
              String sqlQuery = "insert into emp values(1,'chandra',38000,'N')";
              System.out.println(sqlQuery);
              stmt.executeUpdate(sqlQuery);
              con.close();
       }

}

int no = stmt.executeUpdate(sqlQuery);
The above method always return the integer value, refers the number of rows affected in the database.
public class UpdateEmployeeDataByName
{

       public static void main(String[] args) throws SQLException, ClassNotFoundException
       {
              Class.forName(ConnectionPropertiesOracle.DRIVER_CLASS);
              System.out.println("Driver class is registered");
              Connection con = DriverManager.getConnection(ConnectionPropertiesOracle.URL, ConnectionPropertiesOracle.USER_NAME,
                      ConnectionPropertiesOracle.PASSWORD);
              System.out.println("Connection Object:"+con);
              Statement stmt = con.createStatement();
              System.out.println("Statement Object:" + stmt);
              String query = "update emp set salary = 37800 where ename = 'chandra'";
              System.out.println(query);
              Integer updatedRecords = stmt.executeUpdate(query);
              System.out.println(updatedRecords + " Row(s) updated.");
              con.close();
       }

}

·        To develop a jdbc program which could be retrieve records from the database we need to use select query. To send select query to the database we need to use executeUpdate(). This will return ResultSet object. As part of this object we have records. In this we get resultset pointer. By default this pointer position is "0". If we want to read records we will change the pointer position record to first record. Then we can read records. For moving pointer we have next() method.
·        Once we moved the pointer we can read records for this we need to use the getXXX() method, based on the oracle data type we use propermethod
public class RetriveRecords
{

       public static void main(String[] args) throws ClassNotFoundException, SQLException
       {
              Class.forName(ConnectionPropertiesOracle.DRIVER_CLASS);
              System.out.println("Driver is registered");
              Connection con = DriverManager.getConnection(ConnectionPropertiesOracle.URL,ConnectionPropertiesOracle.USER_NAME,ConnectionPropertiesOracle.PASSWORD);
              System.out.println("Connection Object:"+con);
              Statement stmt = con.createStatement();
              System.out.println("Statemtn Object:"+stmt);
              String query = "select * from emp";
              System.out.println(query);
             
              ResultSet rs = stmt.executeQuery(query);
              while (rs.next())
              {
                     System.out.println(rs.getInt("eno"));
                     System.out.println(rs.getString("ename"));
                     System.out.println(rs.getInt("salary"));
                     System.out.println(rs.getString("is_deleted_ind"));
              }
       }

}
·        By using getString() we can get any type of data but it is not recommended way to use it
·        If we want to read data from the database we have two types
1.       Rs.getString("Column Name");
2.       Rs.getString("column Index");
·         Column index start from 1
public class RetriveRecords
{

       public static void main(String[] args) throws ClassNotFoundException, SQLException
       {
              Class.forName(ConnectionPropertiesOracle.DRIVER_CLASS);
              System.out.println("Driver is registered");
              Connection con = DriverManager.getConnection(ConnectionPropertiesOracle.URL, ConnectionPropertiesOracle.USER_NAME,
                      ConnectionPropertiesOracle.PASSWORD);
              System.out.println("Connection Object:" + con);
              Statement stmt = con.createStatement();
              System.out.println("Statemtn Object:" + stmt);
              String query = "select * from emp";
              System.out.println(query);

              ResultSet rs = stmt.executeQuery(query);

              while (rs.next())
              {
                     System.out.println(rs.getInt(1));
                     System.out.println(rs.getString(2));
                     System.out.println(rs.getInt(3));
                     System.out.println(rs.getString(4));
              }
       }

}

Prepared Statement

·         Prepared statement also used to sent query to the database server
·         This statement improve the performance of the database server.
Req: procedure to create prepared statement
1.       Register the driver class
2.       Create the statement object
3.       Create the prepared statement object by passing ? to the values
4.       Pass the values to the ? marks
5.       Execute query
6.       Close the connection
EX:
public class RetriveRecordsByName
{

       private static final String driver = ConnectionPropertiesOracle.DRIVER_CLASS;
       private static final String url = ConnectionPropertiesOracle.URL;
       private static final String user = ConnectionPropertiesOracle.USER_NAME;
       private static final String password = ConnectionPropertiesOracle.PASSWORD;

       private static Connection con = null;
       private static Scanner scanner;

       public static void main(String[] args) throws ClassNotFoundException, SQLException, FileNotFoundException
       {

              try
              {
                     Class.forName(driver);
                     con = DriverManager.getConnection(url, user, password);
                     String query = OurBundle.getBundle().getString("select_emp_record_by_name");
                     System.out.println(query);
                     PreparedStatement pstmt = con.prepareStatement(query);
                     scanner = new Scanner(new File("src/EmpName.txt"));
                     String name = scanner.nextLine();
                     pstmt.setString(1, name);
                     ResultSet rs = pstmt.executeQuery();
                     ResultSetMetaData metadata = rs.getMetaData();
                     int colCount = metadata.getColumnCount();
                     while (rs.next())
                     {
                           for (int i = 1; i <= colCount; i++)
                           {
                                  String colunmName = metadata.getColumnName(i);
                                  System.out.println(colunmName + "\t" + rs.getString(colunmName));
                           }
                     }
              } finally
              {
                     try
                     {
                           con.close();
                     } catch (SQLException e)
                     {
                           System.out.println(e.getMessage());
                     }
              }

       }

}

How the prepared statement improves the performance of the database?
1.       When-ever sql query send to the database server. First data base server checks the query syntax. If syntax is improper system throws error to the client
2.       Syntax is correct system check for all the objects which are mentioned in the query(table name, column names, view names)
3.       Now oracle server parse the sql query to the database understand query
4.       Now the database server prepares the multiple algorithms to get the data from database
5.       Now server stores query along algorithms in the SGA(System Global Area)  memory
6.       The database server picks the best suitable algorithm at that time
7.       Now data base execute suitable algorithm and retrieve the data
·        Oracle bind variables improve the performance of the database query, If we are sending same query with different values. The following is an example
·        Variable eno number;
·         exec :eno:=10
·        Print eno;
·        When we use the parameters like mention above we then oracle server improves the performance of application, here only values are changing not query, because of this system no need to convert query every time.
·        In Prepared statement we will use the  ? for the variable.
·        Prepared statement will not improve the performance of the query at first time, if we doesn't pass the bind variables statement always works the normal query.
Closing the connection:
·         Whenever we get the connection from the database, it is a physical connection, until we release the connection database will not revoke the connection. For releasing the connection we use close() method.
              con.close();

callable statement:

·         Creating procedure in database
create or replace procedure proc as
begin
                insert into emp values(10,'abc',38000,'N');
end;
/
·         If any errors occurred  while creating of procedure we need to use show err command
·         Exec proc_name is used for executing procedure
·         While developing procedure we can pass parameters. We can pass two types of parameters
1.       In parameters
2.       Out parameters
·         Procedure with in parameters
create or replace procedure proc(veno in number,vename in varchar2,vsal in number,vdelete in varchar2) as
begin
                insert into emp values(veno,vename,vsal,vdelete);
end proc;
/

·         The following is the java program which can call the procedure

public class ExecutingProcedure
{

       /*
        * create or replace procedure proc
        * as
        * begin
        *     insert into emp values(10,'abc',38000,'N');
        * end;
        * /
        */
       public static void main(String[] args) throws SQLException
       {
              DriverManager.registerDriver(new OracleDriver());
              Connection con = DriverManager.getConnection(ConnectionPropertiesOracle.URL, ConnectionPropertiesOracle.USER_NAME,
                      ConnectionPropertiesOracle.PASSWORD);
              CallableStatement cstmt = con.prepareCall("{call proc}");
              System.out.println(cstmt.execute());
              con.close();
       }

}
·         The following program which calls the procedure that procedure contains the parameters
public class ExecutingProcedureWithParameters
{

       /**
        * create or replace procedure proc(veno in number,vename in varchar2,vsal
        * in number,vdelete in varchar2) as begin insert into emp
        * values(veno,vename,vsal,vdelete); end proc; /
        * @throws SQLException
        */
       public static void main(String[] args) throws SQLException
       {
              DriverManager.registerDriver(new OracleDriver());
              Connection con =            DriverManager.getConnection(ConnectionPropertiesOracle.URL,ConnectionProper       tiesOracle.USER_NAME,ConnectionPropertiesOracle.PASSWORD);
              CallableStatement cstmt = con.prepareCall("call proc(?,?,?,?)" );
              cstmt.setInt(1, 10);
              cstmt.setString(2, "chandra");
              cstmt.setInt(3, 38000);
              cstmt.setString(4, "N");
              System.out.println(cstmt.execute());
              con.close();
       }

}
·         Following procedure will return the out parameter
create or replace procedure addition(no1 number, no2 number,sum out number) as
begin
                sum := no1+no2;
end;
/
public class FindSum
{

       /**
        * create or replace procedure addition(no1 number, no2 number,sum out
        * number) as begin sum := no1+no2; end; /
        * @throws SQLException
        */
       public static void main(String[] args) throws SQLException
       {
              DriverManager.registerDriver(new OracleDriver());
              Connection con = DriverManager.getConnection(ConnectionPropertiesOracle.URL,ConnectionPropertiesOracle.USER_NAME,ConnectionPropertiesOracle.PASSWORD);
              CallableStatement cstmt = con.prepareCall("call addition(?,?,?)");
              cstmt.setInt(1, 10);
              cstmt.setInt(2, 20);
              cstmt.registerOutParameter(3, Types.NUMERIC);
              cstmt.execute();
              System.out.println(cstmt.getInt(3));
              con.close();
       }

}
Resultset types
·         Result set is two types
1.       Forward only result set
2.       Bi directional result set
·         If result set moves only one direction we can say it as forward only result set
·         Result set moves in both direction we can say then as bi directional result sets
·         Once we get the result set object we can find the result set pointer position by using rowed().
·         By default we get the forward only result set
·         To create the bi directional result set we need to create the statement object by passing parameters. Those parameters are
1.       Result type
2.       Result set concurrency
ResultSet types:
1.       ResultSet.TYPE_FORWARD_ONLY
2.       ResultSet.TYPE_SCROLL_SENCITIVE
3.       ResultSet.TYPE_SCROLL_INSENSITIVE
RESUT SET CONCURENCY
1.       ResultSet.CUNCOR_READ_ONLY
2.       ResultSet.CUNCOR_UPDATABLE\
public class ForWardReadOnly
{

       /**
        * @param args
        * @throws ClassNotFoundException
        * @throws SQLException
        */
       public static void main(String[] args) throws ClassNotFoundException,      SQLException
       {
              Class.forName(ConnectionPropertiesOracle.DRIVER_CLASS);
              System.out.println("Driver is registered");
              Connection con =            DriverManager.getConnection(ConnectionPropertiesOracle.URL,ConnectionProper       tiesOracle.USER_NAME,ConnectionPropertiesOracle.PASSWORD);
              System.out.println("Connection obj:"+con);
              Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,        ResultSet.CONCUR_READ_ONLY);
              System.out.println("Statement Object:"+stmt);
              String query = "select * from emp";
              System.out.println(query);
              ResultSet rs = stmt.executeQuery(query);
              System.out.println("Current row number "+rs.getRow());
              //rs.previous();  Invalid operation for forward only resultset :     previous
              con.close();
       }

}
·         As part of database we have 5 records once we got the result set object if any one change the data in DB, if result set is sensitive then we get updated data, result set is insensitive we didn't get the updated data
·         If result set pointer is invisible getRow() return the "0". Absolute(int) is used to place the result pointer at the specified position
public class SensitiveResultSet
{

       /**
        * @param arg
        * @throws SQLException
        * @throws IOException
        */
       public static void main(String[] args) throws SQLException, IOException
       {
              DriverManager.registerDriver(new OracleDriver());
              Connection con = DriverManager.getConnection(ConnectionPropertiesOracle.URL, ConnectionPropertiesOracle.USER_NAME,
                      ConnectionPropertiesOracle.PASSWORD);
              Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
              String query = "select eno,ename,salary from emp";// It doesn't support
                                                                                                  // * here
              ResultSet rs = stmt.executeQuery(query);
              while (rs.next())
              {
                     rs.refreshRow();//need to check once not working
                     System.out.println(rs.getString(1));
                     System.out.println(rs.getString(2));
                     System.out.println(rs.getString(3));
              }
       }

}

·         Following query update the data in the result set
public class CuncorUpdatable
{
       public static void main(String[] args) throws SQLException, IOException
       {
              DriverManager.registerDriver(new OracleDriver());
              Connection con = DriverManager.getConnection(ConnectionPropertiesOracle.URL, ConnectionPropertiesOracle.USER_NAME,
                      ConnectionPropertiesOracle.PASSWORD);
              Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
              String query = "select eno,ename,salary from emp";// It doesn't support
                                                                                                  // * here
              ResultSet rs = stmt.executeQuery(query);
              rs.absolute(3);
              rs.updateString("ename", "ravi");
              rs.refreshRow();
              System.out.println(rs.getString(2));
              con.close();
       }

}
·         Following query update data in database also
public class UpdateDatabseData
{

       public static void main(String[] args) throws SQLException, IOException
       {
              DriverManager.registerDriver(new OracleDriver());
              Connection con = DriverManager.getConnection(ConnectionPropertiesOracle.URL, ConnectionPropertiesOracle.USER_NAME,
                      ConnectionPropertiesOracle.PASSWORD);
              Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
              String query = "select eno,ename,salary from emp";// It doesn't support here
              ResultSet rs = stmt.executeQuery(query);
              rs.moveToInsertRow();
              rs.updateInt(1, 8);
              rs.updateString(2, "ravi");
              rs.updateInt(3, 38000);
              rs.insertRow();
              con.close();
       }

}

BatchUpdates

·         Batch updates improve the performance of java application. In batch updates we will collect all the queries and send all of them in single statement.
public class BatchUpdates
{
       private static final Logger log = LogFile.getLogger("BatchUpdates.log");
       private static final String driver =     ConnectionPropertiesOracle.DRIVER_CLASS;
       private static final String url = ConnectionPropertiesOracle.URL;
       private static final String username =   ConnectionPropertiesOracle.USER_NAME;
       private static final String password = ConnectionPropertiesOracle.PASSWORD;

       private static Connection con = null;

       public static void main(String[] args)
       {

              try
              {
                     Class.forName(driver);
                     con = DriverManager.getConnection(url, username, password);
                     String query =       OurBundle.getBundle().getString("insert_records_in_emp");
                     System.out.println(query);
                     PreparedStatement pstmt = con.prepareStatement(query);
                     for (int i = 1; i < 100; i++)
                     {
                           pstmt.setInt(1, i);
                           pstmt.setString(2, "name");
                           pstmt.setDouble(3, i * 100);
                           pstmt.setBoolean(4, Boolean.FALSE);
                           pstmt.addBatch();
                           log.info(query + i);
                     }
                     int[] a = pstmt.executeBatch();
                     for (int i : a)
                     {
                           System.out.println(i);
                     }
                     System.out.println("Data inserted");
              } catch (ClassNotFoundException e)
              {
                     log.error(e.getMessage());
              } catch (SQLException e)
              {
                     System.out.println(e.getMessage());
                     log.error(e.getMessage());
              } finally
              {
                     try
                     {
                           con.close();
                     } catch (SQLException e)
                     {
                           log.error(e.getMessage());
                     }
                     log.info("connection is closed");
              }
       }
}

Transaction

·         Performing sequence of steps in single transaction is called transaction
·         Whenever we establish the connection we started the transaction. In this transaction we can send multiple queries. Once we have done our work we need to end the transaction. When we end transaction it will start another transaction. JDBC driver start the transaction when we fire query it will end the transaction.
·         To control above behaviour we need to call method.setAutoCommit(false)
·         After ending the transaction commit()/rollback().
public class Transactions
{
       private static final Logger log = LogFile.getLogger("Transactions.log");
       private static final String driver = ConnectionPropertiesOracle.DRIVER_CLASS;
       private static final String url = ConnectionPropertiesOracle.URL;
       private static final String user = ConnectionPropertiesOracle.USER_NAME;
       private static final String password = ConnectionPropertiesOracle.PASSWORD;
       private static Connection con = null;

       public static void main(String[] args)
       {
              try
              {
                     Class.forName(driver);
                     con = DriverManager.getConnection(url, user, password);
                     con.setAutoCommit(false);
                     Statement stmt = con.createStatement();
                     String empQuery = "insert into emp values(1,'chandra',38000,'N')";
                     String addressQuery1 = "insert into address values(1,1,'nml','cuddapah','AP','N')";
                     String addressQuery2 = "insert into address values(2,1,'hadapsar','pune','MP','N')";
                     System.out.println(empQuery);
                     stmt.executeUpdate(empQuery);
                     System.out.println(addressQuery1);
                     stmt.executeUpdate(addressQuery1);
                     System.out.println(addressQuery2);
                     stmt.executeUpdate(addressQuery2);
                     con.commit();
              } catch (SQLException e)
              {
                     log.error(e.getMessage());
                     try
                     {
                           con.rollback();
                           System.out.println("roll backed");
                           log.error("Transaction rollbacked");
                     } catch (SQLException e1)
                     {
                           System.out.println(e1.getMessage());
                           log.error(e1.getMessage());
                     }
              } catch (ClassNotFoundException e)
              {
                     log.error(e.getMessage());
                     System.out.println(e.getMessage());
              } finally
              {
                     log.info("Success");
                     try
                     {
                           con.close();
                     } catch (SQLException e)
                     {
                           System.out.println(e.getMessage());
                           log.error(e.getMessage());
                     }
              }
       }

}

MetaData

·         Data about data is called metadata. An item which gives the more information about data is called as metadata. In JDBC we have two types of metadata
1.       ResultSetMataData
2.       DataBaseMetaData
·         ResultSetMetaData is an object which gives extra data about the result set object. This will gives the data about column names and number of columns
·         Data which tells about the data base details is called as database meta data.
·         The following class is for result set metadata
public class MyResultSetMetaData
{
       public static void main(String[] args) throws SQLException
       {
              DriverManager.registerDriver(new OracleDriver());
              Connection con = DriverManager.getConnection(ConnectionPropertiesOracle.URL, ConnectionPropertiesOracle.USER_NAME,
                      ConnectionPropertiesOracle.PASSWORD);
              Statement stmt = con.createStatement();
              ResultSet rs = stmt.executeQuery("select * from emp");
              ResultSetMetaData rsMetaData = rs.getMetaData();

              System.out.println(rs);
              int numberOfColumns = rsMetaData.getColumnCount();
              System.out.println(numberOfColumns);
              for (int i = 1; i <= numberOfColumns; i++)
              {
                     System.out.print(rsMetaData.getColumnName(i) + "\t");
              }

              System.out.println();
              while (rs.next())
              {
                     for (int i = 1; i <= numberOfColumns; i++)
                     {
                                  System.out.print(rs.getString(i));
                     }
              }
       }
}
·         The following class specifies the database metadata
public class MyDataBaseMetaData
{

       public static void main(String[] args) throws SQLException
       {
              DriverManager.registerDriver(new OracleDriver());
              Connection con = DriverManager.getConnection(ConnectionPropertiesOracle.URL,ConnectionPropertiesOracle.USER_NAME,ConnectionPropertiesOracle.PASSWORD);
              DatabaseMetaData dbMetaData = con.getMetaData();
              System.out.println(dbMetaData.getCatalogSeparator());
              System.out.println(dbMetaData.getCatalogTerm());
              System.out.println(dbMetaData.getDatabaseMajorVersion());
              System.out.println(dbMetaData.getDatabaseMinorVersion());
              System.out.println(dbMetaData.getDriverName());
              System.out.println(dbMetaData.getDriverVersion());
       }

}

JDBC Driver types

·         In jdbc drivers play the major role, as part of drivers we have code for interact with database server. Without driver we can't communicate with DB.
·         Connection is the important interface. When we get this connection we can interact with DB. This connection interface holds the connection object of database.
·         There are 4 types of divers are available. Those are
1.       Type-1 driver (JDBC-ODBC bridge)
2.       Type-2 Driver(pure native driver)
3.       Type-3 driver (network protocol)
4.       Type-4 driver(pure java )
·        If we want to communicate with DB we need to use any of the driver
Type-1 driver:
Procedure to configure type-1 driver
1.       Install the client s/w so it will get the OCI functions(Oracle s/w)
2.       Install ODBC driver
3.       Get the jdbc driver for communicating with ODBC driver(SMS supplies type-1 driver
4.       Configure the odbc driver
·         Startà control panel -àadmisnistrative toolsàODBC Data Source 32 bità
·         The above configuration launch the dialog box and in that box select DSN
·         Clicks on add button and fill the detailsClicks on add button and fill the details
Click on finish
·         Create the java application
public class Type1
{
       public static void main(String[] args) throws SQLException
       {
//            DriverManager.registerDriver(new JdbcOdbcDriver());
              Connection con = DriverManager.getConnection("jdbc:odbc:driver1",ConnectionPropertiesOracle.USER_NAME,ConnectionPropertiesOracle.PASSWORD);
              System.out.println(con);
       }
}
Disadvantages:
1.       User is responsible to install all the s/w
2.       Machine dependent
3.       It is slow
Advantage:
·         It will work with any database
Type-2 driver
If we want to use the type 2 driver we have to use JNI API. This directly calls the oci functions
Disadvantages:
·         This driver is machine dependent so nobody provided implementation for this driver.
Type-3 driver:
Advantage:
This driver is more secure driver
Disadvantages:
We have to buy this driver

Type-4 driver:
Advantages:
·         This is plat from dependent
·         It directly communicate with DB without oci
·         The best driver for web based application
The internal code of type 4 driver uses the  java network programming
Disadvantage
·         If we want to communicate with any db we need to set that jar file to class path.

JNDI

·         JNDI is also an API, which is also used for the communicating with directory server. Which is also released by SMS.
·         Directory server stores the data in the form of objects, Db stores data in the form of Objects
·         Directory server store the data small amount of data and database server stores the data in the form of rational records.
·         Database server respond the sql queries and directory servers doesn't
·         Directory server stores the data once retrieve multiple times, those gives the best performance.
·         There are so many directory servers available like LDAD (Light Wight Directory Server),DNS(Domain naming server),ADS(Active directory server),NDS(Novel Directory Server).
·         All the classes and interfaces related to JNDI are available in jse API. Those are present into the javax.naming package.
·         Most important interface is Context and implementation class is Initial context.
·         If we want to create application which stores the JNDI, first we need to start the web-logic server and then we need to pass the parameters. Following is the example of JNDI
public class JNDIConnection
{
       @SuppressWarnings("unchecked")
       public static void main(String[] args) throws NamingException
       {

              @SuppressWarnings("rawtypes")
              Hashtable t = new Hashtable();
              t.put(Context.INITIAL_CONTEXT_FACTORY,   "weblogic.jndi.WLInitialContextFactory");
              t.put(Context.PROVIDER_URL, "t3://localhost:7001/");
              t.put(Context.SECURITY_CREDENTIALS, "weblogic");
              t.put(Context.SECURITY_PRINCIPAL, "weblogic");

              Context context = new InitialContext(t);

              context.bind("name", "Chandra");
              System.out.println(context.lookup("name"));
              context.rebind("name", "Reddy");
              System.out.println(context.lookup("name"));
              context.unbind("name");

              context.createSubcontext("FirstYear");
              context.bind("FirstYear.name", "chandra");
              System.out.println(context.lookup("FirstYear.name"));
              context.rebind("FirstYear.name", "Reddy");
              System.out.println(context.lookup("FirstYear.name"));
              context.unbind("FirstYear.name");
       }
}

Connection Pool


1.       Start the web logic server
2.       Run the following url(http://localhost:7001/console)
3.       Select the data source
4.       Click on create new
5.       Provide the connection pool properties
Click on next
Do nothing and click on next

Procedure to create connection pool program:
1.       Get the data source object
2.       Get the connection object from the datasource
3.       Execute query
4.       Close the connection
public class ConnectionPool
{
       @SuppressWarnings("unchecked")
       public static void main(String[] args) throws NamingException, SQLException
       {

              @SuppressWarnings("rawtypes")
              Hashtable t = new Hashtable();
              t.put(Context.INITIAL_CONTEXT_FACTORY,   "weblogic.jndi.WLInitialContextFactory");
              t.put(Context.PROVIDER_URL, "t3://localhost:7001/");
              t.put(Context.SECURITY_PRINCIPAL, "weblogic");// user name
              t.put(Context.SECURITY_CREDENTIALS, "weblogic");// password

              Context context = new InitialContext(t);
              DataSource ds = (DataSource) context.lookup("connectionPool");
              Connection con = ds.getConnection();
              Statement stme = con.createStatement();
              ResultSet rs = stme.executeQuery("select * from emp");
              while (rs.next())
              {
                     System.out.println(rs.getString("eno"));
              }
              con.close();
       }
}
Procedure to create connection pool program by using DBCP
To create this program first we need to set classpath to common-collection.jar, common-dbcp.jar,commons-pool.jar files
public class DBCPConnectionPool
{

       public static void main(String[] args) throws SQLException
       {
              BasicDataSource ds = new BasicDataSource();
              ds.setDriverClassName(ConnectionPropertiesOracle.DRIVER_CLASS);
              ds.setUrl(ConnectionPropertiesOracle.URL);
              ds.setUsername(ConnectionPropertiesOracle.USER_NAME);
              ds.setPassword(ConnectionPropertiesOracle.PASSWORD);
              ds.setInitialSize(1);
             
              Connection con = ds.getConnection();
              Statement stmt = con.createStatement();
              ResultSet rs = stmt.executeQuery("select * from emp");
              ResultSetMetaData rsMetaData = rs.getMetaData();

              System.out.println(rs);
              int numberOfColumns = rsMetaData.getColumnCount();
              System.out.println("Number of columns: "+numberOfColumns);
              for (int i = 1; i <= numberOfColumns; i++)
              {
                     System.out.print(rsMetaData.getColumnName(i) + "\t");
              }

              System.out.println();
              while (rs.next())
        {
                     for (int i = 1; i <= numberOfColumns; i++)
                     {
                                  System.out.print(rs.getString(i));
                     }
        }

       }

}



No comments:

Post a Comment