Top Banner

of 162

Natraj Jdbc

Jul 06, 2018

Download

Documents

Dvsr prasad
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/17/2019 Natraj Jdbc

    1/162

      JDBC

    a)When it is given to begin the execution.

    b)In the process of creating first object for the class.

    c)When Class.forName()is called.

    Q:- How can we develop java application without main method?

    Ans:-

    public class DemoApp1

    {

    static

    {

    int a=10;

    System.out.println(“square of a =”+a*a); 

    System.exit(0);

    }

    }

    The above code runs in all java versions up to jdk1.6 and in the

    initial release of jdk1.7 but not in other version.

    API: Application Programming InterfaceHere the word interface is no way related to java interface. It is

    used

    Having English meaning based/platform;

  • 8/17/2019 Natraj Jdbc

    2/162

     APIs are base for developers to develop software applications.

     Every language technology and framework gives different API.

     In c language API mean set of function which is in the form of

    header files.

     C++ API means set of functions, classes which comes in the

    form of header files.

     In java API means classes, interfaces, enums, annotations

    which come in form of packages.

    There are 3 types of API.

    (i)  Built-in APIs (given by language/technology/framework)

    (ii)  User-Defined APIs (given by programmer)

    (iii)  Third party APIs (given by other than above two)

    Popular Java APIs(built in api)

     

    Utility api(java.util and its sub package)

      Jdbc api(java.sql, javax.sql and its sub packges)

    JD C : =>

    Persistence : =>

    Saving data for long time and manage data for

    long time is called persistence.

     The process of saving and managing data for long time is

    called persistence.

  • 8/17/2019 Natraj Jdbc

    3/162

     The data stored in variables, objects of application allocates

    memory in different part of RAM only during the application

    execution. This data, memory vanished once the application is

    completed because RAM is temporary memory. In order to

    overcome this problem we should write application data to

    secondary memory like hard disk to persistence.

    Terminologies:-

    (1)  Persistence store

    (2) 

    Persistence data

    (3)  Persistence logic

    (4)  Persistence Technology

      CRUD/CURD/SCUD

    o  C-Create(insert)

    R- Read (select)o  U-Update(modify)

    o  D- Delete

    Terminologies:-

    The place where data will be saved

    and managed is called persistence store

     

    Persistence Store:-

    The data of persistence store is called

    persistence data.

     Persistence Operation:-

  • 8/17/2019 Natraj Jdbc

    4/162

      The insert, update, delete and select

    operations performed on persistence data is called persistence

    operations. These are also called CURD/CRUD/SCUD

    operations.

     The logic that is used to perform persistence operation is called

    persistence logic. 

    Eg:- IO Steam code, JDBC code hibernate code.

     The technology that can be used to develop persistence logic is

    called persistence technologies. 

    Eg:- JDBC, Hibernate (Framework), spring jdbc(framework) 

     Every application contains some logic like presentation,

    business, service and persistence logic and etc. 

     The logic that provides user-interface to end user to view

    result to supply inputs is called presentation logic. 

     The logic that generates result is called business logic/service

    logic. 

     The logic that persist data is called persistence logic. 

      Sample Application:-

     R ead student details like no, name, marks (3 subjects)

    presentation logic. 

     Calculate total average Service logic. 

    Total=m1+m2+m3;

    Avg=(m1+m2+m3)/3;

  • 8/17/2019 Natraj Jdbc

    5/162

     Generating ranks for students service logic. 

     Display Result Presentation logic. 

     Save result, inputs to Db table persistence logic 

    I/O Stream

     Java Application Files

    Serialization & Deserialization

     Java Application jdbc(sql queries) DataBase

    SoftWare(RDBMS)

    (oracle, Sybase, mysql -------

    --)

    Serialization =>

    Process of capturing object data and writing that datato file is called serialization. 

    Deserialization :=>

    Reading data form file and constructing object having

    that data is called deserialization. 

    Limitations with files as persistence stores:-

     

    No Security. 

     Cannot maintain huge amount of data. 

     No constraints can be applied. 

     No sql support. 

  • 8/17/2019 Natraj Jdbc

    6/162

     We cannot define relationship. 

     Update and delete operation are very complex. 

     Merging and comparison of data is very complex. 

    To overcome these problems use database software as persistence

    store.

    The Advantages are:-

     Security

     Sql support

     

    Allows to apply constraints, allow to define relationship.

     Merging and comparison of data is very easy and etc.

      Conclusion:-

     Use files as persistence store in small scale application

     

    Use database software as persistence store in large scaleapplication.

    Eg: –  Banking application, Insurance application etc.

     To get interaction between operating system and external devices

    of computer like printer we need support of external device of

    computer like printer we need device driver.

    \

  • 8/17/2019 Natraj Jdbc

    7/162

     We need jdbc diver as bridge between java application and

    database software. It converts java calls to database calls and vice

    versa.

     Non java application use odbc driver to interact with database

    software.

     We cannot use ODBC driver directly in our java applications.

  • 8/17/2019 Natraj Jdbc

    8/162

     Some jdbc driver internally uses odbc driver support while

    interacting with database software. Some other JDBC driver

    directly interacts with database software.

     We can get jdbc driver from three vendors :-

    (a)  Sun Microsystem (oracle corporation)

    (b)  Database Vendor (Recommended)

    (c)  Third party vendors.

     We can get odbc driver from three vendors.

    (a) 

    Xopen

    (b)  Database vendors (recommended)

    (c)  Third party vendors.

     Jdbc 4.x Api packages.

     java.sql, java.sql packages (core packages)

     Javax.sql.RowSet, javax.sql.rowset.Serilizable,javax.sql.Rowset.api(advanced packages)

  • 8/17/2019 Natraj Jdbc

    9/162

     

    Continue

    2015-03-12

  • 8/17/2019 Natraj Jdbc

    10/162

     What is the difference between language and technology?

    Programming language:-

    These are raw material directly installable

    software as raw material having basic features of application

    development.

     Programming language define syntax (Rule), Symantec (structure)

    of programming.

     Language is base for creating technology, framework, operating

    system and database software etc.

     Eg –  c, c++, java etc.

    Technologies:- 

    These are software specification

    having set of rules and guideline to develop software by using

    programming language.

     Technology is not installable but technology based software

    installable.

     Working with these software is nothing but working with

    technologies.

      Jdbc is technology software specification that gives set of rules

    and guidelines to develop Jdbc driver using java language. Jdbc is

    not installable. Working with jdbc driver is nothing but working

    with JDBC .

  • 8/17/2019 Natraj Jdbc

    11/162

      There are two types of technology are:-

    (1)  Open technology:-

    These technologies are rules and guidelines

    open for multiple vendor companies to develop the software.

    Eg:- All jsp, jee technology (jdbc, jndi, servlet etc)

    (2)  Proprietary technology:-

    The vendor that has given these technologies are only

    allowed to develop software based on the technologies.

    Eg:-All Microsoft Technology.

  • 8/17/2019 Natraj Jdbc

    12/162

     Since all jdbc driver given by different vendor companies are

    coming based on the common rules and guidelines of jdbc

    technology so we can work with all these jdbc driver in a

    common way in the application development.

     The interfaces of jdbc API packages represent rules of jdbc

    technology and the classes of jdbc API packages represent

     guidelines of jdbc technology.

     Every jdbc driver is a collection of classes implementing various

    interfaces of jdbc Api packages and all these classes contain logic

    to interact with sertain database software and to send and execute

    sql queries in database software.

    Q:- What is jdbc?

    Ans :- It is an open java technology given by sun microsystem having

    set of rules and guidelines to develop jdbc driver for differencedatabase software.

    ODBC :->

    It is an open technology given by Xopen has set of rules

    and guidelines to develop odbc driver for different database software.

     Every technology gives one API. This API will be used by vendor

    companies as rules and guidelines to develop software‖s .The same

    API will be used by programmers to work with technology based

    software in the application development.

  • 8/17/2019 Natraj Jdbc

    13/162

     Eg. The API of jdbc technology will be used by vendor companies

    as rules and guidelines to develop jdbc drivers and the same api

    will be used by programmer in application development to

    activate jdbc drivers and to develop jdbc persistence logic.

     java.sql.Driver (interface)

    ^

    | extends

    sun.jdbc.odbc.jdbcOdbcDriverInterfacd (Interface)

    ^

    | implements

    sum.jdbc.odbc

     Even though multiple class in every jdbc driver we just know

    diver class name in order to activate and use these jdbc driver in

    our java application.

     Every Jdbc driver is identified with its driver class. It is the class

    supplied by vendor company of jdbc driver implementing

     java.sql.Driver Interface directly or indirectly.

     Upto jdk1.7 we get one built in jdbc driver given by sum

    Microsoft in rt.jar file. This jdbc driver is identified with its driver

    class .

  • 8/17/2019 Natraj Jdbc

    14/162

      sum.jdbc.odbc.JdbcOdbcDriver

    (package )|(class name)

    The above jdbc driver class implements java.sql.DriverInterface

    directly as shown below:-

     Java.sql.Driver(interface)

    ^

    | extends

    Sun.jdbc.odbc.JdbcOdbcDriverInterface(interface)

    ^

    | Implements

    Sum.jdbc.odbc.JdbcOdbcDriver(class)

     Along with window operating system installation we get multiple

    ODBC driver every odbc driver is identified with its DSN.

     There are three types of DSNs available thses are: -

    (1)  User Dsn :- specified currently logged in user.

    (2)  System Dsn : - Spcific to all the window users of a

    computer.

    (3)  File system Dsn :- Sharable in the network.

    Procedure to create dsn for Microsoft odbc driver for oracle

    Step 1) Make sure that oracle is installed.

    Step 2) Add oracle installation related bin directory to path

    environment variable (My Computer)

  • 8/17/2019 Natraj Jdbc

    15/162

    Step 3) My computer property Advance system settings

    environment variablesuser/System variablesvariable name:

    path

    Value: ;c:\oracle

    xe\app\oracle\porduct\10.2.0\server\Bin;ok(3).

    Steps (3) create user DSN for micro soft odbc driver for oracle(window

    7/8)

    C:\window\syswow64\odbca32userDsn(tab) addMicrosoft

    odbc for oracle/oracle xefinished.

    Data source name :oraDsn

    Description :[dsn for microsoft odbc driver oracle]

    User name: scott

    Server :

    Server:

    This value is optional while working with local oracle. Thisvalue is mandatory while working with centralize network. (Gaither

    Dsn String from admin)

    Vendor companies can use one of the five mechanism

    /architecture/methodology to develop jdbc driver for different Data

    Base software based on the rule and guideline of jdbc technology .

    They are :--

    (1)  Type-1 driver (jdbc-odbc bridge driver)

    (2)  Type-2 driver (Native API /partly java driver)

    (3)  Type-3 driver (Net protocol/all java driver)

  • 8/17/2019 Natraj Jdbc

    16/162

    (4)  Type-4 driver (Native protocol/All java driver)

    (5)  Type-5 driver (not yet confirmed by sum micro system so there

    is no technical name)

    Partial Architecture of Type-1 jdbc driver:-

    This type-1 driver is designed to talk with Data base software

    directly. It is designed talk the support of odbc driver to interact

    with database software.

    We can use one type-1 jdbc driver to talk with multiple database

    software by take support of multiple odbc driver.

     The jdk supplied build-in jdbc driver is given based on type-1

    architecture. Its driver class name issum.jdbc.odbc.JdbcOdbcDriver.

     So for only sun Microsoft is giving type-1 diver along with jdk

    software installation .(up to jdk 1.7)

     Every java application contain one built in service called

    Drivermanager service.

     

    Having the capability to manage set of jdbc dirvers.

     TO access these services in our application we can use

     java.sql.DriverManager class.

  • 8/17/2019 Natraj Jdbc

    17/162

     To user JdbcDriver in our java application it must be register with

    driver manager service for this we need to keep JdbcDriver class

    object in DriverManager service by using register driver

    manager.

    //Registering jdbc type-1 driver

    //creating odbc driver class object

    sun.jdbc.odbc.JdbcOdbcDriver obj1=new

    sun.jdbc.odbc.JdbcOdbcDriver();

    //Register jdbc driver

    DriverManager.registerDriver(obj1)

    Property of registerDriver(--) method 

    Public static void registerDriver(java.sql.Driver driver) throws

    SQLExceptionThe parameter type of registerDriver(--) method is java.sql.Driver(I), so

    we must call that method having implementation class object of that

    interface all jdbcdriver class implements java.sql.Driver(I) directly or

    indirectly due to this we can call registerDriver(--) having jdbc driver

    class object. Notes:-

    Sun.jdbc.odbc.JdbcOdbcDriver(c)

    Implement java.sql.Driver(I) directly or indirectly.

    Three important statements of method parameter types.

  • 8/17/2019 Natraj Jdbc

    18/162

    Note: - we cannot create object of interface and abstract classes.

    A) If method parameter type is interfaces we call that method having

    implementation class object of that interface (refer above)

    B) If method parameter is a abstract class. We call that method

    having one subclass object of that abstract class as argument.

    C)  If method parameter type is concrete class, we call that method

    having either that class object or one of its subclass object as

    argument.

     

     Jdbc application means java application with jdbc code as

    persistence logic to manipulate database data.

      Jdbc application acts as front end and database software acts as

    back end.

     What end user see and operate is called front end, what he cannot

    see call backend.

     Backend(database software) responds based on front end

    interaction.

    Standard steps to develop jdbc application.

    a) Register jdbc driver with Driver Manger Service (Activate jdbc

    driver)

    b) Established the connection with database software.

    c) Create statement object.

    d) Send and execute Sql Queries in database software.

  • 8/17/2019 Natraj Jdbc

    19/162

    e) Gaither results from database software and process the results.

    f)  Close connection with database software.

    Registering jdbc driver is nothing but placing jdbc driver classobject with driver manager service.

    This is mandatory to use jdbc driver in our java applications.

     Establishing connection means creating communication channel

    between java application and database software.

      Jdbc statement object acts as a vehicle between java application

    and database software.

     To send SQL queries to database software to execute sql queries in

    database software and to gather result back to java application

     Once operation with database software is completed it is

    recommended to close connection with database software.

    Q:- Write a jdbc application to establish connection between javaapplication and oracle software using type-1 jdbc driver.

    Software Set Up: -

     Java any version (jdk 1.7)

    Oracle any version (oracle 11g)

    Type-1 jdbc (Built in with jdk software dsn create for Microsoft odbc

    driver for oracle (“oradsn) 

    import java.sql.*;

  • 8/17/2019 Natraj Jdbc

    20/162

    public class ConnTest

    {

    public static void main(String args[]) throws Exception

    {

    //Register odbcDriver(type 1)

    //Create jdbc diver class obj

    sun.jdbc.odbc.JdbcOdbcDriver obj=new

    sun.jdbc.odbc.JdbcOdbcDriver();

    // register diver

    DriverManager.registerDriver(obj);

    //Establish the connection with database software

    Connection

    con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");

    if(con==null){

    system.out.println("Connection not established");

    }

    else

    system.out.println("connection is established");

    }//main method closed

    }//class closed.

    27-02-2015

  • 8/17/2019 Natraj Jdbc

    21/162

     getConnection method uses given jdbc url , database password details

    to use to appropriate jdbc driver, other details while establishing the

    connection with database software

     Jdbc url syntax 

    < main protocol >: : sub name

    In case of type-1 driver the url is jdbc:odbc:oradsn

    Name of dsn

    “jdbc” –  main protocol

    “odbc” –  sub protocol

    Oradsn –  sub name (dsn)

     The jdbc driver class name, jdbc url will change based on the

     jdbc driver we use and database software we use.

     

    Protocol is set of rules followed by two parties who wants toparticipate in communication.

     There are two types of protocol.

    (1)  Application level protocol

     Gives set of rules to get

    communication between software services.

    Eg: - http, jdbc:odbc

    (2)  Network level protocol :

  • 8/17/2019 Natraj Jdbc

    22/162

       Gives set of rules to get

    communication between two physical computer of

    network.

    Eg: - Tcp/ip.

    In the above application

    DriverManager.getConnection(“jdbc:odbc:oradsn”,”scott”,”tiger”)

    method performs.

    (1)  Picks up the registered type-1 jdbc driver form DriverManager

    service. Based on the protocol “jdbc:odbc” specified in the url.

    (2)  Type-1 jdk dirver uses odbc driver for oracle based on the dsn

    that is specified (oradsn”). 

    (3)  Using both driver (Type-1 odbc driver) the connection

    between java application and database software will be created

    and the jdbc connection object will be return back to the jdbcconnection object will be returned back to java application

    representing that connectivity.

    Q:-

    Connection

    con=DriverManager.getConnction(“jdbc:odbc:oradsn”,”scott”,”tiger”)

    When java.sql.Connection is an interface how can we say

    DriverManager.getConnection(-, -, -) is returning jdbc

    connection object.

    Ans: 

  • 8/17/2019 Natraj Jdbc

    23/162

      Jdbc connection object means it is not object of java.sql.connection .

    It is the object of that underlying jdbc driver supplied java class that

    implements java.sql.Connection(I). Since this class name changes based

    on the jdbc driver we use we never specify this class name in our jdbc

    aplications.

    In type-1 jdbc driver this name is

    “sun.jdbc.odbc.JdbcOdbcConnection” and this class implements java

    connection(I) as shown below.

     To know class name by object we can use getClass() method.

    System.out.println(“connection object name:”+con.getClass()); 

  • 8/17/2019 Natraj Jdbc

    24/162

     Interface reference variable can reference its implementation

    class object. DriverManager.getConnection(-, -, -) return the

    implementation class object .

      Java.sql.Connection(I) and we are referring that object with

     java.sql.Connection(i) reference variable (that is “con”). 

    Properties of getConnection(-, -, -)

    public static getConnection(String url,String user,String pwd)

    throw SQLException

    The return type of DriverManager.getConnection is

     java.sql.Connection that means this method returns

    implementations class object of java.sql.ConnectionInterface.

    Three type of statements on method return types: -

    1. If method return type is abstract class then method returns one

    subclass object of that class.2. If method return type is interface then method retrun

    implementation class object of that interface.

    3. If method return type is concrete class then method return

    either that concrete class object or one of its subclass objects. 

    02-28-2015 

  • 8/17/2019 Natraj Jdbc

    25/162

    Instead of writing two line of code to register jdbc driver with

    DriverManager service we can use the following one line of

    code for the same purpose.

    class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 

    class.forName(-) load the given jdbc driver class.

    In that purpose the static block of driver class executes.

    This static block contains logic to create jdbc driver class

    object and logic to create jdbc driver class object and logic to

    register that object with DriverManager service by calling

    DriverManager.registerDriver() method.

    The static block of sun.jdbc.odbc.JdbcOdbeDriver class

    looks like this.

    Static

    {Try

    {

     JdbcOdbcDriver jdbcodbc=new JdbcOdbcDriver();

    DriverManager.registerDriver(jdbcodbcdriver);

    }

    Catch(Exception)

    {

    e.printStackTrace();

    }

  • 8/17/2019 Natraj Jdbc

    26/162

    }

    Different ways of reading input from keyboard.

    1) Using Scanner Class (jdk 1.5 onbord)

    2) Using Command line arguments

    3) Using user defined system property

    4) Using BufferedReader

    5) Using java.io.Console (jdk 1.6)

    import java.io.*;

    import java.util.*;

    public class ReadInput

    {

    public static void main(String args[]) throws IOException

    {Scanner sc =new Scanner(System.in);

    System.out.println("Enter Name-1 : ");

    String name1=sc.next();

    String name2=args[0];

    String name3=System.getProperty("myName");

    //using stream

    BufferedReader br=new BufferedReader(new

    InputStreamReader(System.in));

    System.out.println("Enter name-4 :");

  • 8/17/2019 Natraj Jdbc

    27/162

    String name4=br.readLine();

    //Using console

    System.out.println("Enter Name-5 : ");

    Console cons=System.console();

    String name5=cons.readLine();//display value

    System.out.println(name1+" "+name2+" "+name3+" "+name4+"

    "+name5);

    }>javac ReadInput.java

    }> java – DmyName=Raja3 ReadInput Raja2

    Setting command line argument

    Setting System property value

    Once specified passing command line argument is mandatory

    Once specified passing system property is optional.

    Q: - can you explain different way of registering jdbc DriverManagerwith DriverManager service 

    Approach-1: - 

    sun.jdbc.odbc.JdbcOdbcDriver obj=new

    sun.jdbc.odbc.JdbcOdbcDriver(obj);

    import java.sql.*;

    public class ConnTest

    {

    public static void main(String args[]) throws Exception

    { //Register odbcDriver(type 1)

  • 8/17/2019 Natraj Jdbc

    28/162

      //Create jdbc diver class obj

    sun.jdbc.odbc.JdbcOdbcDriver obj=new

    sun.jdbc.odbc.JdbcOdbcDriver(); // register diver

    DriverManager.registerDriver(obj); //Establish the conncection with

    database software

    Connection

    con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");

    if(con==null)

    {

    System.out.println("Connection not established");

    }

    else

    System.out.println("connection is established");

    }//main method closed}//class closed

     In process of creating first object to any class jvm load that class

    and executes static block of that class.

     In the above code same jdbc driver will be register with

    DriverManager service.

     

    First time because of static block of jdbc driver class.

     Second time because of explicit call given to

    DriverManager.registerDriver(-) method.

  • 8/17/2019 Natraj Jdbc

    29/162

    Note: - Registering same jdbc driver is a bad practice so the

    approach-1 is bad approach.

    Approach-2: -

    DriverManager registerDriver(new

    sun.jdbc.odbc.JdbcOdbcDriver());

    Note: - This approach is very much similar to approach -1 so it is

    not recommended to use.

    DriverManager.registerDriver(new

    sun.jdbc.odbc.JdbcOdbcDriver());

    Connection

    con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");

    import java.sql.*;

    public class ConnTest2

    {

    public static void main(String args[]) throws Exception

    {

    DriverManager.registerDriver(new

    sun.jdbc.odbc.JdbcOdbcDriver());

    Connection

    con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");

    if(con==null)

  • 8/17/2019 Natraj Jdbc

    30/162

      {

    System.out.println("Connection not established");

    }

    else

    System.out.println("connection is established");

    }//main method closed

    }//class closed

    Approach-3

    sun.jdbc.odbc.JdbcOdbcDriver obj=new

    sun.jdbc.odbc.JdbcOdbcDriver();

    import java.sql.*;

    public class ConnTest3

    {

    public static void main(String args[]) throws Exception

    {

    sun.jdbc.odbc.JdbcOdbcDriver obj=new

    sun.jdbc.odbc.JdbcOdbcDriver();

    database software

    Connection

    con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");

    if(con==null)

  • 8/17/2019 Natraj Jdbc

    31/162

      {

    System.out.println("Connection not established");

    }

    else

    System.out.println("connection is established");

    } }

    Approach-4 

    new sun.jdbc.odbc.JdbcOdbcDriver();

    Approach-4 is similar to approach-3 so it is not recommended to

    use

    Note: -

    In approach- 3&4 the driver will registered only for one time butexplicitly created object of driver class will be wasted.

    new sun.jdbc.odbc.JdbcOdbcDriver(); // register diver

    Connection

    con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");

    import java.sql.*;

    public class ConnTest4

  • 8/17/2019 Natraj Jdbc

    32/162

    {

    public static void main(String args[]) throws Exception

    {

    new sun.jdbc.odbc.JdbcOdbcDriver(); // register diver

    Connection

    con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");

    if(con==null)

    {

    System.out.println("Connection not established");

    }

    else

    System.out.println("connection is established");

    }//main method closed}//class closed

    Approach-5

    public class ConnTest5 extends sun.jdbc.odbc.JdbcOdbcDriver

    {

    public static void main(String args[]) throws Exception

    {

  • 8/17/2019 Natraj Jdbc

    33/162

      Connection

    con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");

     In the above code when jvm load contest class it also loads its

    super class called Driver class in this process static block driver

    class execute and driver will be registered.

     The above code is not recommended because it does not let our

    application class to extends from other class like from applet,

    HTTPservlet

    import java.sql.*;

    public class ConnTest5 extends sun.jdbc.odbc.JdbcOdbcDriver

    {

    public static void main(String args[]) throws Exception

    {

    Connectioncon=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");

    if(con==null)

    {

    System.out.println("Connection not established");

    }

    else

    System.out.println("connection is established");

    }//main method closed

  • 8/17/2019 Natraj Jdbc

    34/162

      }//class closed

    Approach-6

    class.forName(“sun.jdbc.odbc.JdbcOdbeDriver)  This is a recommended approach because it registered the driver

    only for one time and does not create any west object for driver

    class

    import java.sql.*;

    public class ConnTest6

    {

    public static void main(String args[]) throws Exception

    {

    if(Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")==null)

    {

    System.out.println("Connection not established");

    }

    else

    System.out.println("connection is established");

    }//main method closed

    }//class closed

    Approach=7

  • 8/17/2019 Natraj Jdbc

    35/162

    public class contest

    {

    public static void main(String args[]) throws IOException

    {

    Class.forName(args[0])

    Connection con=new

    DriverManager.getConnection(“jdbc:odbc:oradsn”,”scott”,”tiger”); 

    import java.io.*;

    import java.sql.*;

    class ConnTest7

    {

    public static void main(String args[]) throws Exception

    {

    Class.forName(args[0]);

    Connection

    con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");

    if(con==null)

    {

    System.out.println("Connection not established");

    }

    else

    System.out.println("connection is established");

  • 8/17/2019 Natraj Jdbc

    36/162

      }//main method closed

    }//class closed

    Approach-8Public class contest

    {

    Public static void main(String args[]) throws Exception

    {

    String driver=System.getProperty(“myDriver”); 

    Class.forName(driver);

    Connection

    con=DriverManager.getConnection(“jdbc:odbc:oradsn”,”scott”,”tiger”)

    ;

    }}

    This is similar to approach-7 so not recommended to use.

    import java.io.*;

    import java.sql.*;

    class ConnTest8

    {

    public static void main(String args[]) throws Exception

    {

    String driver=System.getProperty("mydriver");

    Class.forName(driver);

  • 8/17/2019 Natraj Jdbc

    37/162

      Connection

    con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");

    if(con==null)

    {

    System.out.println("Connection not established");

    }

    else

    System.out.println("connection is established");

    }//main method closed

    }//class closed

    >javac ConnTest8.java

    >java – Dmydriver=sun.jdbc.odbc.JdbcOdbeDriver ConnTest8

    Approach-9

    As part of DriverManager class initialization it attempt to load jdbcdriver class that are there in fixed system property so driver will be

    registered automatically.

    Class contest

    {

    Public static void main(String args[]) throws IOException

    {

  • 8/17/2019 Natraj Jdbc

    38/162

     Connection

    con=DriverManager.getConnection(“jdbc:odbc:oradsn”,”scott”,”tiger”)

    ;

    }

    }

    import java.sql.*;

    public class ConnTest10

    {

    public static void main(String args[]) throws Exception

    {

    Connection

    con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");

    if(con==null)

    {System.out.println("The conncetion is not establish");

    }

    else

    System.out.println("the conncetion is establish");

    }//>javac ConnTest9.java

    }//>java – Djdbc.driver=sun.jdbc.odbc.JdbcOdbcDriver ConnTest

    Approach-10

  • 8/17/2019 Natraj Jdbc

    39/162

    Since type-1 driver is built in driver of jdk there is no need to

    registering that driver with driver manager service.

    Public class TestConn10

    {

    Public static void main(String args[]) throws Exception

    {

    Connection

    con=DriverManager.getConncetion(“jdbc:odbc:oradsn”,”scott”,”tiger”)

    ;

    import java.sql.*;

    public class ConnTest10

    {

    public static void main(String args[]) throws Exception{

    Connection

    con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");

    if(con==null)

    {

    System.out.println("The conncetion is not establish");

    }

    else

    System.out.println("the conncetion is establish");

  • 8/17/2019 Natraj Jdbc

    40/162

      }

    }

    Write a jdbc application that use stud

    details based on the given start end rang of student no.

    Select * from student where sno>=100 and sno

  • 8/17/2019 Natraj Jdbc

    41/162

      Connection

    con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");

    //create statement object

    Statement st=con.createStatement();

    //prepare SQL Queries

    //select * from student where sno>100 and sno

  • 8/17/2019 Natraj Jdbc

    42/162

      rs.close();

    st.close();

    con.close();

    }

    }

    Q: - Write a jdbc application to get student details based on the given

    city name.

    Q: - Write a jdbc app empno, ename, sal, job details of employee based

    on the given dept no.

    select empno, ename, sal, job from emp where deptno=10;

    while processing resultSet use those index for column value in order

    they stored in result set obj not in the order they are available in

    database

     

    While retrieving value from Resutlset record we can users.getString() method if u don‖t know the data type. 

     We can call rs.getxxx(--) method to retrieve the value of record

    either with cols name of cols index.

    Assignment:-1

    Write a program that returns students details based on given initial

    characters of student Name?

    Assignment: -2

  • 8/17/2019 Natraj Jdbc

    43/162

      Write a program that returns Employee details based on the

     given three designation.

    Q: - When java does not support pointer why does it throws

    NullPointer exception

     When we invoke method on reference variable that holds null

    value we will get “NullPointerException”. 

    Date d=null;

    d.getYear();//Throws NullPointerException

    -> Here the word “pointer” is no way related to c/c++ pointers. It is

    purely used by having “Dictionary meaning” indicating method is on

    reference variable that points to null value.

    SOLUTION:

    Date d=null;

    d=new Date();d.getYear(); //Does not throw NullPointerException

    import java.sql.*; (implicit pkg import)

    import java.sql.DriverManager;

    Important java coding standards;

    1) Write proper comments.

    2) Avoid implicit pkg imports prefer explicit pkg imports

  • 8/17/2019 Natraj Jdbc

    44/162

  • 8/17/2019 Natraj Jdbc

    45/162

    Q: - Write a jdbc application to get count of emp table record

    Select count(*)from emp;

    employee name,jobdetails for the emp who is having highest salaryselect ename,empno,job from emp where sal=(select max(sal) from

    emp);

    If resultSet object contain exactly one record then process the resultSet

    using if(rs.next) method.

     If ResultSet contain zero or more record then process that

    RecordSet by using while(rs.next()) method.

     Once we close jdbc connection it automatically closes relevant

    statement, ResultSet object.

     Prototype of createStatement()

    Public Statement createStatement() throws SQLException

     

    Prototype of executeQuery(--)

     Public ResultSet executeQuery(String qry) throws

    SQLException

    To send and execute non-select sql query in database software we

    use executerUpdate() method. This method return numeric value

    representing number of record that are affected it will return integer.

  • 8/17/2019 Natraj Jdbc

    46/162

    Q:- Write a jdbc application to delete student details based on

     given student no.

    Delete is a non-select sql query so use executeUpdate() method

    for sql query execution.

    Refer->aap-2 page no — 19,20

    There is no necessity of dealing with ResultSet object.

     Sql query that is execute through in database s/w through sql

    command it is not auto committed.

     

    Sql queries that is executing by coming from jdbc application

    execute in data base s/w by enabling auto commit.

    Write a jdbc application to update student name, address, based on

     given student number.

    Update students set sname=‖raja‖,sad=‖Delhi‖ where sno=901; 

    App-5 page- 22 and 24

    2015-03-06 

     Notepad, notepad++, editplus are editors

     Eclipse, MyEclipse, NetBeans and etc,… are IDEs

     IDE provides total environment that is required for the

    development and integration of the project.

    Eclipse:-

     Type: IDE for java environment

     Vendor: Eclipse or

  • 8/17/2019 Natraj Jdbc

    47/162

     Version: 4.4 (Eclipse luna)

     Open source (freeware)

     To download s/w : ww.ecllipse.org

     (as zip file: Extract zip file for installation)

     Two flavors of Eclipse

    1)  JSE flavor (sdk)

    2)  Jee flavors

     www.nataraz.in/software

    Q: - Write a jdbc application to insert record into student table while

     gathering details from end users?

    Procedure to application by eclipse IDE

    Step-1) Launch eclipse ide by choosing its workspace( a folder where

    all project will be saved) folder.Step-2) Create java project.

    File->new->project->Project name (jdbc proj-1)finish

    Step- 3 Develop the above jdbc application in com.nt package of src

    folder.

    a) Create package(Right click on src foldernewpackagecom.nt

    b) 

    Right click on “com.nt” packagenew classname:InsertTest

    InsertTest.java

    Refer App4 page no:20.

    Ctrl+space bar gives main()

  • 8/17/2019 Natraj Jdbc

    48/162

    Ctrl+shift+o

    Step-4 run the application

    Right click in source filerun as java Appuse run as button of the

    menu bar.

    To change JRE of the java project in eclipse

    Right click on project build path libraries table remove existing Jre

    Add library JRE System librarynext

    Installed jre — add-standard vm next JRE home[c:\porgram files

    (x86)\....--> select jdk  finish.

    xany

     toString () method called on exception object just used to called

    exception object that is raised.

     printStack() method called on object elaborated details that is

    raised.When exception is raised in java method the stack memory of the

    method will be filled up with exception related messages. TO print

    those messages on console monitor we need to use printStackTrace()

    method.

    From jdk 1.7try with resource is intro where the resource in try will

    be close automatically at the end of try without closing them explicitly.

    Try(Scanner sc=new Scanner(System.in))

    {

  • 8/17/2019 Natraj Jdbc

    49/162

    ..

    }

    The “Sc” will be closed automatically at the end of try block. 

    Using try with Resource for jdbc code

    -

    Class InserTest

    {

    psvm()

    {

    try(

    Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”)) 

    {

    catch(exception e){

    e.printStackTrace();

    }

    try(conncetion con=DM.getConnection(-,,);

    Statement st=con.createStatement())

    {

    Int res=st.executeUpdate(“delete from student where sno=10”); 

    If(res==0)

    Sop(“record not delete”); 

  • 8/17/2019 Natraj Jdbc

    50/162

    Else

    Sop(“record deleted”); 

    }//main

    }//class

    2015-03-07 

     Notepad, notepad++, editplus are editors

     

    Eclipse, MyEclipse, NetBeans and etc,… are IDEs 

     IDE provides total environment that is required for the

    development and integration of the project.

    Eclipse:-

     Type: IDE for java environment

     Vendor: Eclipse or

     Version: 4.4 (Eclipse luna)

     Open source (freeware)

     To download s/w : wwweclipse.org

     (as zip file: Extract zip file for installation)

     Two flavors of Eclipse

    3) 

     JSE flavor (sdk)

    4)  Jee flavors

     www.nataraz.in/software

  • 8/17/2019 Natraj Jdbc

    51/162

    Q: - Write a jdbc application to insert record into student table while

     gathering details from end users?

    Procedure to application by eclipse IDE

    Step-1) Launch eclipse ide by choosing its workspace( a folder where

    all project will be saved) folder.

    Step-2) Create java project.

    File->new->project->Project name (jdbc proj-1)finish

    Step- 3 Develop the above jdbc application in com.nt package of src

    folder.

    c) Create package(Right click on src foldernewpackagecom.nt

    d) Right click on “com.nt” packagenew classname:InsertTest

    InsertTest.java

    Refer App4 page no:20.

    Ctrl+space bar

     gives main()Ctrl+shift+o

    Step-4 run the application

    Right click in source filerun as java Appuse run as button of the

    menu bar.

    To change JRE of the java project in eclipse

    Right click on project build path libraries table remove existing Jre Add

    library JRE System librarynext

    Installed jre — add-standard vm next JRE home[c:\porgram files

    (x86)\....--> select jdk  finish.

  • 8/17/2019 Natraj Jdbc

    52/162

    xany

     toString () method called on exception object just used to called

    exception object that is raised.

     printStack() method called on object elaborated details that is

    raised.

    When exception is raised in java method the stack memory of the

    method will be filled up with exception related messages. TO print

    those messages on console monitor we need to use printStackTrace()

    method.

    From jdk 1.7try with resource is intro where the resource in try will

    be close automatically at the end of try without closing them explicitly.

    Try(Scanner sc=new Scanner(System.in))

    {..

    }

    The “Sc” will be closed automatically at the end of try block. 

    Using try with Resource for jdbc code

    -

    Class InserTest

    {

    psvm()

  • 8/17/2019 Natraj Jdbc

    53/162

    {

    try(

    Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”)) 

    {

    catch(exception e)

    {

    e.printStackTrace();

    }

    try(conncetion con=DM.getConnection(-,,);

    Statement st=con.createStatement())

    {

    Int res=st.executeUpdate(“delete from student where sno=10”); 

    If(res==0)

    Sop(“record not delete”); Else

    Sop(“record deleted”); 

    }//main

    }//class

    Can be execute both select and non-select query by using single

    method call Yes possible by using execute() method

     This method return type is Boolean.

    Prototype

  • 8/17/2019 Natraj Jdbc

    54/162

    ………………. 

    Public Boolean execute(String qry) throws SQLException

     This method returns “true” when it executes “select” SQL Query. 

    To get ResutlSet of this select SQL Query use getResultSet()

    method.

     This method returns values that represents number of records

    that are affected because of this non-select Query use

     getUpdateCount() method

    For example application - ref-6 page no 24.

    358

    Working with execute method is not industry standard because it does

    not give sql result directly more ever we need to call method separately

     go gather sql query result (like getResultSet(), getUpdateCount)

     Conclusion:

     Use executeQuery(_) to send and execute select  – SQL QUERY

    IN database s/w.

     Use executeUpdate(-) to send and execute non-select sql

    query in database s/w

     Jdbc application to create database table in database s/w.

    Note: - create table, drop table and alter table are non-select query.

    So we should use executeUpdate () to send and execute these method

    in sql query database s/w.

  • 8/17/2019 Natraj Jdbc

    55/162

     In real scenario ddl query execution does not takes place

    through jdbc code only temp table will be created and dropped to

     jdbc code

     In every company separate db team will maintain to design the

    table will be maintain this team will responsible to execute ddl

    form sql prompt

    Write a ddl application to

    Executing ddl query through jdbc application is not industry standard

    because the end result of these queries execution is not same in all the

    driver more ever db team is responsible to design table for the project.

      Jdbc application is not alternate for sql prompt thse are front end

    application interacting with database software support end user.

     

    Miscellaneous command like desc cannot beexecuted through jdbc application.

     In one jdbc application we can have multiple connection,

    statement , ResultSet 0bj using one connection object you can

    create one or more statement object

     Using one statement object crate one or more ResultSet object

     

    U can use one ResultSet object to send and execute one or more

    sql queries. In database s/w.

    Q can we develop java application without user defined class?

    Possible with enum.

  • 8/17/2019 Natraj Jdbc

    56/162

    Every enum is special java class internally.

    2015-03-09

    Understanding internals of DriverManager.getConnection(-,-,-)_

    Connection

    con=DriverManager.getConnection(“jdbc:odbc:oradsn”,”scott”,tiger”); 

    1) Prototype

    Public static Connection getConnection(String url,String user,

    String pwd);

     

     getConnection(-,-,-) is the static method DriverManager()

      getConnection(-,-,-) getRegister jdbc driver class object based

    on the given url(protocol & sub name) and calls connect() on

    that object.

     The connect() of jdbc driver class creates and returns

    implementation class object Connection(I) to getConnection(-,-,_) method and getConnection(-,-,-)returns object to our

    application.

  • 8/17/2019 Natraj Jdbc

    57/162

    Understanding internals of createStatement() method

  • 8/17/2019 Natraj Jdbc

    58/162

    Satatement st=con.createStatement();

     

    (a) createStatement() is non-static method declared in

     java.sql.Connection(I).

    Prototype: -

    Public statement createStatement();

    (b)  createStatement contains implementation in the

    implementation class of java.sql.Connection(I) that is

    sun.jdbc.odbc.JdbcOdbcConnection(c) in type-1 driver.

    (c) createStatement() method definition contains logic to create and

    the implementation class object of java.sql.Statement(I) .That is

    object of sun.jdbc.odbc.JdbcOdbcStatement(C) in type-1 diver.

    Understanding the internals of executeQuery(-) method

    ResultSet rs=st.executeQuery(“select U from students”); 

  • 8/17/2019 Natraj Jdbc

    59/162

     

    1) executeQuery(-) is non-execute(-)is non-static method declared

    in java.sql.Statemnet(i)

    Prototype:

    public ResultSet executeQuery(String qry) throws SQLException2) executeQuery(-) is implemented in jdbc driver supplied java class

    that implements java.sql.Statement(I). In type-1 driver that class

    name is

    “sun.jdbc.odbc.JdbcOdbcStatement”. 

    3) executeQuery(-) internally calls getResutlSet() method.

    4) 

    This getResutlSet() contains logic to crate and return the

    implementation class object “java.sql. ResultSet(I). 

  • 8/17/2019 Natraj Jdbc

    60/162

     

    2015-03-10

    There are 5 mechanisms/architectures to develop jdbc drivers based on

    the rules and guide lines of jdbc technology

    a) Type-1 driver (Jdbc odbc bridge driver)

    b) Type-2 driver (Native API /Partly java driver)

    c) 

    Type-3 driver(Net protocol /All java Driver)

    d) Type-4 driver(native protocol/ All-.java driver)

    e) Type-5 driver(No nick name) (Not officially confirmed by Sun

    Ms)

     All odbc drivers and some jdbc drivers (type2) locate and

    communicate with Db software by using vendor DB library.

     In windows environment this vendor db library comes in the

    form of .dll file along with Db software installation. (in oracle

    it is oci.dll)

     Every odbc driver and every vendor db library is specific to one

    DB software.

  • 8/17/2019 Natraj Jdbc

    61/162

     

    Advantages

     One Type-1 driver can interact multiple database software by

    taking the support of odbc drivers , vendors db libraries

     Since odbc drivers ,vendor db libraries are available for all db

    software we can use this driver to interact with All Db software

     This is built-in driver of jdk so there is no need of arranging this

    driver separately.

    Disadvantage

     This driver performance is poor so not suitable for big

    application.

     Since vendor DB libraries are required at client side we cannot

    use driver for untrusted applet to DB software communication.

     This is not industry standards jdbc driver.

     Suitable for testing apps

     Removed from jdk from java 8 onward.

     This driver must be arranged separately.

  • 8/17/2019 Natraj Jdbc

    62/162

     

    Applets are two types:-

    1) Trusted Applet

    (it perform read and write operation on file system.

    2) Un-Trusted applet

    Can‖t perform read and write operation on file system.(No virus). 

    When we install either complete oracle or client oracle (that

    contains only sql plus we will get vendor db of oracle).

    Type-2

    Advantages: -

    1) No odbc drivers are required

  • 8/17/2019 Natraj Jdbc

    63/162

    2) Gives little bit good performance compare to type-1 driver.

    Disadvantage

    1) This driver performance is not good for large scale projects.

    2) Since vendor DB library is required ate client side, this

    driver cannot be used for untrusted applet to dB software

    communication.

    3) This driver is not industry standard diver.

    4) For every DB software we need separate type-2 jdbc driver.

    Type-4

    Advantages:

    1) This gives good performance compare to type-1, type-2

    divers and suitable for large scale project

    2) Totally developed in java so it is platform independent.

  • 8/17/2019 Natraj Jdbc

    64/162

    3) No odbc drivers, vendors DB libraries are required at client

    side so this driver is suitable for untrusted Applet to DB

    software communication.

    4) This driver can be downloaded dynamically to our

    computer from internet.

    5) This driver industry standard driver.

    Disadvantages;

    1) For every DB software we need separate tupe-4 driver

    3) 

    We must arrange these drivers separately

     Jdbc connection pool is a factory that conatains set of readily available

     jdbc connection objects before actually ebing used. The advantage are:

     Gives reusability of jdbc objs.

     With min number of jdbc connection objects we can make max

    clients to interact with DB software

     Programmers need not to worry about creating, managing and

    destroying jdbc con objs, All These operations will be taken care

    by jdbc connection pool.

  • 8/17/2019 Natraj Jdbc

    65/162

     

     All connection objs of jdbc con pool represents connectivity with

    same DB software.

      Jdbc con pool for oracle means all con objs represents

    2015-03-11

     

    connectivity with same oracle dB software

  • 8/17/2019 Natraj Jdbc

    66/162

     

    w.r to diagram

    1) Server uses type-1/2 /3/4 driver to interact with database s/W

    And create jdbc con objs in the jdbc con pool

    2) Client app uses type3 driver interact with server and to get con

    obj from jdbc con poo.

    3) Client uses that con obj to create other jdbc objs and to develop

    persistence logic

    4) Client app releases the con obj back to jdbc con pool and that obj

    becomes free to give service other clieents.

    Proxy dummy item that represent present until real items come.

    Proxy server talks with the database s/w on behalf of client

    applications

    There are two types of connection

    a) Direct jdbc connection (created by porgrammser manually)

    Class.forName(“…….”); 

  • 8/17/2019 Natraj Jdbc

    67/162

      Connection con=DM.getConnection(-,-,-);

    b) Pooled connection(Gatherred from jdbc conn pool)

    For related information of all jdbc drivers refer page no-8 to16

    What is jdbc driver that u have used in project if your project is

    standalone/desktop app talking with database s/w or two-tier app

    running outside the server (webserver/proxy server) then use type4/5/

     jdbc driver

     If u r project web application, enterprise app, 3-tier app , n-

    tier app running from the server then use type 3 with type4 or

    type3 with type5 jdbc direr

     Note: - Here type 4/5 driver will be user dot create jdbc con

    objs in jdbc con pool and type3 driver will be used to get conobjs from jdbc con pool.

    Q: -What is the difference between path and class path?

    Ans: -

    PATH:

    It is OS command , can be used in all languages and technologies.

  • 8/17/2019 Natraj Jdbc

    68/162

     To make .exe, .bat, .cmd files of certain folder executable from

    any location of computer we need to worik with PATH

    environment variable (without doing physical copying)

     It is not java command, so it can be use anywhere.

    -

    Example:-

    Problem: -

    E:\Demo

    |run.bat

    Run.bat

    Date

    Time

    Ver

    DirE:\Demos?run.bat(success)

    E\>run

     Run is not an internal or external command (problem)

    Solution

    …………. 

    Add the address of run.bat (E:\Demos) to PATH environment

    variable.

    Computer propertiesadv sys settingsenvironement

    variablesuser/system variables 

  • 8/17/2019 Natraj Jdbc

    69/162

      Variable name: PATH

    VALUE:E:\Demos;;.

    od(3)

    D:\Demos>run(success)

    E:\run Run (success)

    Batch(.bat) allows us to group set of commands into single unit.

      Javac, java, javap, javah and etc.. are the .exe files of

    \bindirectory, so to use them from any folder

    our computer we need to add\bin directory to

    PATH environment variable.

    Important points about environments variable

    1) These names are not case sensitive

    2) 

    Do not value to environment variables form cmd prompt,set form mycomputer prompt

    3) Separate multiple values added to environment variable

    with “;” symbol 

    4) User variable are specific to currently logged in windows

    user, system variables are common to all windows users.

    5) 

    New values added to environment variables are not visible

    old cmd prompts

    6) Always add new values at the beginning of existing values.

    2015-03-12

  • 8/17/2019 Natraj Jdbc

    70/162

     classpath

    if java app uses new apis or third parties apis then the new

    api/third party related directories or jar files must be added to

    classpath in order to make java tools (javac ,java, ….) recognizing

    and using those apis.

     It is a java command and cannot used outside the java.

    Example

    Problem:

    User-defined API /third party api

    E:/Demo1

    |wish.java

    Wish.jva

    package con.nt;

    public class wish{

    public String sayHello()

    {

    return “good morning”; 

    }//>javac – d . wish.java

    }

    Main App

    MainApp.java

  • 8/17/2019 Natraj Jdbc

    71/162

    Import com.nt;

    Public class MainApp

    {

    Public static void main(String args[])

    {

    Wish w=new Wish();

    System.out.println(“w.sayHello()); 

    }}

    D:\work> javac MainApp.java(x)

    Error: Can not find symbols com.nt, wish, sayHello

    Solution: The address location of “com.nt” pkg(E:\Demo) folder to

    ClassPath Environemnt variable.

    ClassPath value=E:\Demos1;.

    Ok(3).D:\work>javac MainApp.java(success)

    D:\work>java MainAp(success)

     Jar file: jar archieve file(java level zip file)

    Creating jar file representing apis

    E:\Demos1>jar cf NtLib .

    C =create jar file.

    F=specify the jar file name.

    To see content of the jar file

    E:\Demos1\jar tf NtLib.jar

  • 8/17/2019 Natraj Jdbc

    72/162

    tGives table of content.

    Adding jar file to classpath

    Variable name :CLASSPATH

    Value:E:\Demos1\NtLib.jar;;

    Ok(3).

    We can also add NtLib.jar file to \jre\lib\ext folder.

    D:\work>javac MainApp.java

    D:\work>Java MainApp

    Note : types of class loader

    CLASSPATH \JAR\LIB\EXT

    FOLDER

    Allows both directory, jar file Allows only jar file

    Visible to multiple installation of

     jdk.

    Specific to each jdk.

    New values are not visible in old

    command prompt

    Visible to old command p

    These values will be used by

    System class loader

    These values will be used by

    extension class loader.

     Set of packages together is called one api.

    Set of apis together is called one library.

  • 8/17/2019 Natraj Jdbc

    73/162

     Jar files represent libraries.

    There are 3 classloaders in jar

    (a)  To load the classes from jdk libraries (rt.jar)

    (b)  Extension ClassLoader

     To load the class from the libraries of

    \jre\lib\ext folder

    © System classLoader

     To load the classes from the libraires (directories/jar files)

    added to CLASSPATH environment variable.

    How can you execute java app any folder of a computer?

    Add the address location of a .class file to CLASSPATH

    environment variable.

    D:\Work

    |

     TestApp.javaTestApp.java

    Public class TestApp

    {

    Public static void main()

    System.o.pln(“hello”); 

    }

    }

    D:\work> jvac TestApp.java

    Variable name classpath value:D:\work1:

  • 8/17/2019 Natraj Jdbc

    74/162

     

    What is the difference between physical database s/w and logical

    database.

    Logical db is a logical partition of physical db s/w .Each logical DB

    contains Db tables , pl/sql procedures, function and tec… 

     In one physical DB s/w (like oracle ,mysql) we can create

    multiple logical DBs for multiple projects of a company on 1

    per project basis.

     In oracle we get one default logical DB and it is identified with

    its SID(Service id).

  • 8/17/2019 Natraj Jdbc

    75/162

     

     

    We call type-1\type-2 jdbc drivers as thick drivers because

    they need more component at client side while using.

     We call type4\type5 jdbc driver as thin drivers because they

    directly talk with DB s/ws without taking support any

    components.

     The oracle corporation SUPPLIED TYPE2 JDBC DIRVER FOR

    OR CALE ID CALLDED “Oracle Oci driver”.

     The Oracle corporation supplied type4 jdbc driver for oracle is

    called “Oracle thin driver”. 

  • 8/17/2019 Natraj Jdbc

    76/162

     

    (oracle corporation supplied type-4 mechanism based jdbc driver for

    oracle)

    Mechanism : type 4

    Target Database software: oracle

     Jdbc driver class: oracle.jdbc.driver.OracleDriver (0r)

    oracle.jdbc.OracleDriver

     Jdbc url:

     jdbc:oracle(protocol)thin(subname):@:(host name

    and port number of oracle):

     Jar files:

    oracle 8i:classes111.jar

    oracle9i: classes12.jarOracle10g:ojdbc14.jar

    oracle11g:ojdbc6.jar.

     Most of vendor are giving jdbc drivers in the form of jar file as

    shown above

     All software installed in our computer will reside in different

    s/w ports. Every s/w port is identified with its port number. In

    windows operating system based computer we have 65535

    software ports in that 1024 are reserved for operating system

  • 8/17/2019 Natraj Jdbc

    77/162

    services. All externally installed software will run on other

    ports in the range 1025 to 65535;

     Oracle default port no: 1521

     MySQL default port no :3306

     To refer a computer being from that computer we use the term

    “localhost”. 

    Procedure to develop jdbc Application by using oracle thin

    drive.

    Step-1) Gather oracle thin driver details.

    Step-2)Add odbc14.jar or odbc6.jar file “classpath”. 

    Variable name: Classpath or in \jar\lib\ext

    folder

    Full path:- C:\Program Files\Java\jdk1.7.0_76\jre\lib\ext\[past here]

    Value:c:\orcleexe\app\orcle\porduct\10.2.0\server\jdbc\lib\odbc14.jar;;.

    --ok(3).

    Step3> Develop jdbc App using oracle thin driver

    SelectTest.java

    ………………. 

    …… 

    ……….same as previous app 

  • 8/17/2019 Natraj Jdbc

    78/162

    ………but write following lines of code to register jdbc driver and to

    establish the conncection.

    //register oracle thin driver with DriverManager service

    Class.forName(“oracle.jdbc.driver.OracleDriver”); 

    //establish the connection

    Connection

    con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:

    xe”,”scott”,”tiger”); 

     jdbc:oracle=protocol

    thin=subname

    :@localhost:1521 host name and port no

    Setp4:-

    Work with Oci driver details(oracle corporation supplied type2 mechanism based jdbc diver for

    oracle)

    Driver class name: oracle.jdbc.driver.OracleDriver (or)

    oracle.jdbc.OracleDriver

    url: jdbc:oracle:oci8:@

     jar file : Same as thin diver.

    Example application:

    All steps are same as oracle thin driver but use the following jdbc url in

    DriverManager.getConnection (-,-,-) method.

  • 8/17/2019 Natraj Jdbc

    79/162

    Connection con=DriverManager.getConnection

    (“ jdbc:oracle:oci8:@xe”,”scott”,”tiger”);

    (  jdbc:oracle) protocol

    sid(xe)

     If the subname is “thin” in the URL then the “oracle thin” driver

    will be used to establish the connection.

     If the subname is “oci8” in the URL then the “oracle oci” driver

    will be used to establish the connection.

      Jar file added to the classpath are not visible to the projects

    created in the IDE but the jar files added to the

     java_home\jar\lib\ext folder are visible to the same.

     To add jar file (like ojdbc14.jar) to the project of Eclipse IDE

    use Right click on the project

     Build path

    add externalachieves browser and select the jar file (ojdbc14.jar)

     While working with any jdbc driver we need to gather

    a) Driver class name

    b)  Jdbc url

     To create jdbc conn pointing to any database s/w we need 4

     jdbc properties

    a) Driver class name

    b)  Jdbc url

    c) Database user name

  • 8/17/2019 Natraj Jdbc

    80/162

    d) Database password

     The class name of jdbc object will change based on the jdbc

    diver we use so we never specify them in our Apps but we

    refer the object of those classes by using common jdbc api

    interface reference variables.

     Java.sql.Statement(I)

    ^

    |extends

     Java.sql.PreparedStatement(i)

    ^

    | extends

     Java.sql.CallableStatement(I)

     

    There are 3 statement object in jdbc programminga) Simple statement object

    (it is the object of jdbc driver supplied java class that

    implements java.sql.Statement(I));

    b) PreparedStatement object

    (it is the object of jdbc driver supplied java class that

    implements java.sql.PreparedStatement object.

    c) CallableStatement object

    (it is the object of jdbc driver supplied java class that

    implements java.sql.CallableStatement. object

  • 8/17/2019 Natraj Jdbc

    81/162

     

    2014-03-14

    LoginAPP

    Checks identity of a user by taking the given username and password

    details .Also verifies them against Database table.

    DB table in oracle

    Saq> create table userlist(uname verchar2(20), pwd verchar2(20));Sql> insert into userlist values(―raja‖,‖rani‖); 

    Sql> insert into userlist values(―king‖,‖kingdom‖); 

    Sql Query of the Application

    Sql> select count(*) from userlist where uname=‖raja‖ and pwd=‖rani1‖ 

    Count(*)

    0 (Invalid credentials)

    LoginApp.java(refer page no-26 application no-8)

    What is sql injection problem?

    Changing the behavior or sql query and application by adding special

    sql instruction (like --) to the query along with the input values is

    called raising sql injection problem. Hackers use this technique to get

    into various accounts by supplying correct user name and wrong

    password.

    Respect to application -8 of booklet.

  • 8/17/2019 Natraj Jdbc

    82/162

     Java LoignApp

    Username :‖raja‖ - -

    Password: hyd (wrong password)

    Output : valid credentials (sqlinjection problem)

    In real scenario persistence logic will not be placed directly in main

    application like main method persistence will be placed in separate

    class called DAO class (Data Access Object class) the java class that

    separate persistence logic form other logic it makes that logic as

    flexible logic to modify and also has reusable logic is called DAO class.

     JdbcProj2

    | src

    |com.nt

    |StudentDAo.java

    |MainApp.java

    package com.nt;

    import java.sql.*;

    public class StudentDAO

    {

  • 8/17/2019 Natraj Jdbc

    83/162

      Connection con=null;

    public void makeConnection()

    {

    try{

    Class.forName("oracle.jdbe.driver.OracleDriver");//establish the connection

    con=DriverMananager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger");

    }//try

    catch(Exception e)

    {

    e.printStackTrace();

    }//catch

    }//makeConneciton()public void getStudentDetails(String city)

    {

    try{

    Statement st=null;

    if(con!=null)

    st=con.createStatement();

    ResultSet rs=null;

    if(st!=null)

    rs=st.executeQuery("select * from students where sadd="+"'"+city+"'");

    if(rs!=null)

    {

    while(rs.next())

    {

    System.out.println("rs.gtInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

    }//while

    }//if

    //close objsif(rs!=null)

    rs.close();

    if(st!=null)

    st.colse();

    }//try

  • 8/17/2019 Natraj Jdbc

    84/162

      catch(Exception e)

    {

    e.printStackTrace();

    }

    }//getStudntDetailspublic void closeConnection()

    {

    try

    {

    if(con!=null)

    con.close();

    }

    catch (Exception e){

    e.printStackTrace();

    }

    }//close connection

    }//class

    package com.nt;

    public class MainApp

    {

    public static void main(String args[])

    {

    //create obj DAO class

    StudentDAO dao=new StudentDAO();

    //call mehods

    dao.makeConnection();

    dao.getStudentDetails("hyd");dao.closeConnection();

    }//main

    }//class

  • 8/17/2019 Natraj Jdbc

    85/162

      Assignment:

    Q: = By using DAO style implementation get the emp details form emp

    table who is having given nth highest salary.

    When  java app sends sql query to databse software ,the database engg of database s/w performs 3

    operations on that SQL Query

    1. 

    Parse operation

    2.  Execution operation

    3. 

    Fetch operation

    Parse-> In this operation the given query will be splited into tokens and the syntax of the query

    will be verified by compiling SQL QUERY;

  • 8/17/2019 Natraj Jdbc

    86/162

    EXECUTE: - The Parsed Query will Optimized and will be executed in database software.

    Fetch: - The results of executed SQL Query will be gathered from database software and will be

    sent to java application client application.

      Simple Statement obj sends raw/static SQL Query to database software , i.e given query goes

    to database software directly wit out any conversions.

      When use simple statements object to execute same SQL Query in database software for

    multiple times either with same values or different values.

    a)  Same Query goes to database s/w for multiple times from java application.

    b)  Same query will be parsed in db s/w for multiple times.

    c)  Same query will be executed in db s/w for multiple times either with same values or diff

    values.

    d) 

    Same query output will be fetched out from db s/w for multiple times.

     

    Performing a), b) operation on same query for multiple times is unnecessary, But

    performing c), d) operations on same query for multiple times is necessary, but we can

    avoid a), b) operation happing for multiple times when we work with simple statement

    object, Due to this we can say simple statement object is not suitable for executing same

    query for multiple times with different values or same values.

    Example:-

    Railway Resrervation App that book 100000 tickets per day should execute same inser query for

    `100000 times to maintains passenger details.

    a)  Same insert query goes to Db s/w from java app to database software for 1,00,000 times:

    100000*0.1=10,000sec

    b)  Same insert query will be parsed in database software for 100,000 times:

    1,00,000*0.1sec=10,000secs

    c)  Same insert queruy will be executed in database software for 1,00,000 times wither with same

    or diff values:100000*0.1=10,000secs

    d) 

    Same insert query output will be fetched out for 100000 times : 100000*0.1=10,000secs

      Performing a), b) operations on same for multiple times is unneccassary on same query, but this

    cannto be avoided while working with simple statement object..

  • 8/17/2019 Natraj Jdbc

    87/162

    Limitations with simple statement object

      Not suitable to execute same query multiple time either with same values or different values (

    Gives performance problem)

      May Raise SQL injection problem. 

     

    Framing query by involving variable sin complex because

    we need to convert java values to sql values in this process. 

      Inserting date values in the in database table by collecting

    values date values in different pattern in complex process. 

      Inserting large object (files) is not possible. 

     

    Improves network traffic between java application and

    database s/w . 

     

    To overcome all these problem we need to work with per-

    compiled sql query with support of jdbc

    perparedSatement objcect. 

    Pre-compiled sql query/Dynamic sql query

     The sql query tahat goes to db s/w from client app with

    or without values and becomes parsed or comiledirrespective of ites executeon is called per-compiled sql

    query.

  • 8/17/2019 Natraj Jdbc

    88/162

      Jdbc prepaearedStatement object represents this per-

    compiled sql queryo of sb s/w being from java app and

    this oject can be useda) To assing multiple set of values to query params.

    b) 

    To execute query for multiple times either with same

    values or diff values

    c) To fetch the query results for multiples times.

    Simple Statement object deals with static /raw sql

    query where as PreparedStatement obj with pre-

    compiled sql query.

    The above Railway ticket reservation example with

    PreparedStatement obj

    a) Insert query oges to Db s/w from java app only for one

    time :1*0.1=0.1 sec

    b) Insert query will be parsed /compiled in databse s/w only

    for one time : 1*0.1=0.1 sec

  • 8/17/2019 Natraj Jdbc

    89/162

    c)  Java app assigns multiple sets values to insert sql query

    and executes that query for multiple times either with

    same or different values :1,00,000*0.1=10,000 secsd) Same insert query output will be fetched out for multiple

    times: 1,00,000*0.1=10,000secs

    Here a), b) operations are taking place on insert query only 1

    time. This improves performance.

     PreparedStatment object suitable for executing same

    query for multiple times either with same values or

    different.

    Based on the above discussion we can say PreparedStatement

    objet is useful in the development of ticket reservation,

    registration and search activities related application

    development.

    Procedure to work with PreparedStatement object;-

    Step-1 ) Prepare SQL Query with place holders /parameters (?)

  • 8/17/2019 Natraj Jdbc

    90/162

    String qry=”insert into students values(?,?,?)”;[parameters

    represent (?) Positions in sql query for which values can be set

    latter]

    Setp-2) send sql query to DB s/w and make that query as per-

    compiled sql query in database s/w and get PreparedStatement

    representing that per-compile object query.

    PreparedStatement ps =con.prepareStatement(qry);

    Con.prepareStatement(0) method

    a) Sends given SQL Query to DB s/w

    b) Makes DB Engg to compile/parse that Query and also to

    make that query as per-compiled SQL Query.

    c) Create and Returns PreparedStatement object back to java

    application representing pre-compiled sql query of

    database s/w.

    Step: -3) set values to Query params/place holders(?) of pre-

    compiled Query using setxxx(-) methods.Ps.setSPs.setInt(1,1001);

    Ps.setString(2,”raja”); 

  • 8/17/2019 Natraj Jdbc

    91/162

    Ps.setString(3,”hyd”); 

    Step:-4) Execute the above pre.compiled sql query of

    database s/w.

    Int result=ps.executeUpdate();

    Step5) Process the result.

    If(result==0)

    Sop(“record not inserted”); 

    Else

    System.out.println(“Record inserted”); 

    Step: -6) To execute the above query for multiple with diffvalues repeat step3 to step 5 for multiple times.

    Step:-7) close jdbc object.

    Write a jdbc app to gather and insert n number of stuendts details in

    database table

  • 8/17/2019 Natraj Jdbc

    92/162

     

    Here we need to execute same “insert” SQL Query w ith diff values

    for multiple times, for this we need to use per-compiled SQL

    Query with the support of jdbc PreparedStatement object.

    Referr application

    IN THE development logic it is always recommended to sql query

    at the top of class as constant value(static final variable var)

    Ex: -private static final String INSERT_STUDENT_QRY

    Don‖t place “*” symbol in select sql query, Always write col names

    in select sql query.

    Select * from student  bad practice( if we add new col in db

    table then problem will come)

    Select sno,sname,sad from student good practice.

    We can use preparedStatement object for both select or non-

    select query exection.Pre-compiled query represented by preparedStatment object can

    be there with parameters or without parameters.

    Executing select query by using preparedStatement object.

    PreparedStatement ps=con.prepareStatement(“Select * from Student”); 

    ResultSet rs=ps.executeQuery();

    Whle(rs.next())

    {

    System.out.println(rs.getInt(1)+””+rs.getString(2)+””rs.getString(3)); 

    }

  • 8/17/2019 Natraj Jdbc

    93/162

    While working with jdbc PreparedStatement object we can place

    parameters in the sql query just representing input values but we

    cannot parameters representing table name, col names and sql

    keywords….. 

    Select * from students (valid)

    Select * from student where sno>=? (valid)

    Select * from student where ?>=? (invalid)

    Select * ? student (invalid)

    Select * ? ? where ?>=? (invalid)

    Note: - using PreparedStatement object we cannot execute DDL queries

    having table name, co names as the parameters.

    Q: How can we execute static SQL Query by using PreparedStatement

    object?Call ps.execute(-),executexxx(-) methods with agrs on jdbc

    preparedStatement object as shown below.

    PreparedStatement ps=con.prepareStatement(“Select * from student”); 

    ResultSet rs=pr.executeQuery(“select * from em”); 

    While(rs.next()) -- executes as static sql query.

    {

    ..

    ..

  • 8/17/2019 Natraj Jdbc

    94/162

    }

    in the above code “select * form student” will not be executed but “select

    * from emp” will be executed as static SQL Query. 

    (Vvi)

    What is the difference between simple statement and

    PreparedStatement?

    Simple statement PreparedStatement

    1. Deals with static sql query2. Suitable for executing query for

    one time without input values.

    3. May raise sql injection problem

    4. Makes database engine to compile

    sql query with input.

    5. Not suitable for date valueinsertion.

    6. Not suitable for large object

    insertion (files)

    7. Improves network traffic b/t java

    app and database s/w(degrades

    the performance)

    8. Using one statement object we

    can send and execute multiple sql

    queries.

    9. We need to convert input values

    1. Deals with pre-compiled sqlquery (dynamic query)

    2. Suitable for executing query for

    multiple times either with same

    or different input values.

    3. Does not raise sql injection

    problem.4. Makes database engine to

    compile without inputs.

    5. Suitable for date value insertion

    6. Suitable

    7. Reduces n/w traffic b/t java app

    and database s/w and improves

    performance

    8. For every sql query we need to

    separate PreparedStatement

    object.

  • 8/17/2019 Natraj Jdbc

    95/162

    of query according to sql syntax. 9. Conversion is not required.

    Why simple Statement object raises sql injection problem and why sam

    problem does not raise in PrepasredStatement.

    Simple Statement obj makes the DB engine of Database software to

    compile sql query with input values, so the special sql instruction (like

    --) that are given along with input values participate in query

    compilation, due to the sql query behavior will be changed during

    execution because of those special sql instructions (--) this is nothing

    but sql injection problem

     PreparedStatement object makes the Database Engine of Database

    s/w to compile sql query without input values and input values

    will be set to query after the compilation of query and before the

    execution of the query, so he special sql instruction (like --) that

    are given along with the given values does not participate in

    query compilation, Due to this they cannot change query

    behavior in the execution of query. This indicates “NOA=sql

    injection problem.

    MySQL

  • 8/17/2019 Natraj Jdbc

    96/162

    TYPE: Database Software

    Version: 5.5

    Vendor: DevX/sun Microsystem/Oracle Corporation

    Open Source

    Port no: 3306

    Default user-name: root

    Password : root (will be chosen during the installation)

    Download: -

    www.oracle.com , www.mysql.com 

    Allow to create logical DBs.

    procedure to create logical database having DB table with

    records.

    Step-1) Launch mysql prog

    Start  mysql mysql 5.5 command line client

    Password (root) which is choosen during installation

    Setp2) create Logical DB NTDb1

    Mysql> Create database NtDB1;

    Step-3) create database table student in NtDb

    |no int

    |sname varchar

    |sadd varchar

    Connect NtDb5

    http://www.oracle.com/http://www.oracle.com/http://www.mysql.com/http://www.mysql.com/http://www.mysql.com/http://www.mysql.com/http://www.oracle.com/

  • 8/17/2019 Natraj Jdbc

    97/162

     

    Create table student (sno int(5),sname, varchar(20) ,sad

    varchar(20))

    Insert into student values(111,‖ramesh‖,‖hyd‖); 

    Commit.

    DevX supplied type4 mechanism based jdbc driver for mysql is

    called Connector/j jdbc driver and This driver details are

    Driver class name: org.gjt.mm.mysql. Driver(0r)

    com.mysql.jdbc.Driver

    url: jdbc:mysql:///

  • 8/17/2019 Natraj Jdbc

    98/162

     

    Procedure to use SQLY0G for MySQL logical DB having DB table

    with records.

    Launch sqlyog

    continue

    new (con1)hostaddress(localhost)Username-root password rootconnect

    right click on root crate database (NtDb6)[name of logical

    database]createNtDb6(right click)create table

    Field name Datatype len

    Pid Int 5

    right click on tableinsert record

    Assignment

    Develop jdbc app that transfers the record from oracle db table to

    my sql table.

    Working with date value 2015-03-19

    While developing various apps we need to insert DOB, DOJ,

    DOMarriage, Bill Date, Expiry date Purchase Date and etc…

    values Database table along with other values.

  • 8/17/2019 Natraj Jdbc

    99/162

     

    Inserting date values as string values in DB table cols is notrecommended because we cannot compare two values and

    we cannot subtract one date values from another date values.

    It always recommended to insert date values in “Date data

    type columns of DB table.

    Different database s/w support different patterns of date

    values.

    Oracle: dd-MMM-yy (10-OCT-80)

    Mysql: yyyy-MM-dd (1980-10-20)

  • 8/17/2019 Natraj Jdbc

    100/162

     

    If we use simple statement object to insert date values we

    must place date value in the query in the pattern which is

    supported by DB s/w.

    If we use PreparedStatement object to insert date value, we

    need to give java.sql.Date class object to jdbc driver through

    SQL Query and driver inserts date value in dB table in pattern

    that is supported by underlying database s/w.

     java.util.Date is the super class of java.sql.Date class and it

    cannot be used to perform Database operations.

     java.sql.Date can be used to perform DB operations…. 

    If you set java.sql.Date class object to jdbc driver representing

    date value then jdbc driver inserts the date value in the

    pattern it supported by underlying database s/w.

    Example application to retrieve different date pattern value and insertthem in database table.

    Refer app-10

    Person_tab(in oracle)

    Ask data of birth from end user and calculate his age.

    To retrieve date values from DB table we can use either

    Simple Statement object or PreparedStatement object. 

    To retrieve Date values form jdbc ResultSet object we can use

    rs.getDate(-) method.

  • 8/17/2019 Natraj Jdbc

    101/162

     

    TO convert java.util.Date class object to String date value use

    format.

    (1) App executes select query using simple Statement or

    PreparedStatement object and get ResultSet object having Date

    values in the form of java.sql.Date class obj.

    (2) Application retrieves java.sql.Date class object to java.util.Date

    class object.

    (3) Application Converts java.sql.Date class objects to java.util.Dateclass object.

    (4) Application uses format(-) of SimpleDateFormat Date class to

    convert java.util.Date class object to String date values.

  • 8/17/2019 Natraj Jdbc

    102/162

     (5) App gives this date value to end user.

    For above diagram based application refer

    If u use rs.getString() method to retrieve date value display in

     yyyy-MM-dd pattern.

    If you use rs.getDate() method to retrieve value there is possibility

    of displaying date value in the pattern that we need.

    parse() method of SimpleDateFormat class converts given String

    date values ot java.util.Date class object.

    format(-) of SimpleDateFormat class convers given java.util.Date

    class obj to string date value.

    //Agecal.p

    import java.util.*;

    public class AgeCalApp{

    public static void main(String args[])

    {

    Scanner sc=new Scanner(System.in);

    System.out.println("Enter DOB(dd-mm-yyyy)");

    String dob=sc.next();

    //convert string date value into java.util.Date class object.

    SimpleDateFormat sdf1=new SimpleDateFormat("dd-MM-yyyy");

    Date udob=sdf1.parse(dob);

  • 8/17/2019 Natraj Jdbc

    103/162

    //get Sys date

    Date sysdate =new Date();

    //calc age

    long ms=(sysdate.getTime()-dob.getTime());

    //long ms=System.currentTimeMillis()-udob.getTime();

    float age=(float)ms/(1000.0f*60*60*24*365);

    System.out.println("Age" +age);

    }

    }

    Q: - Write a jdbc application to copy records from students

    records form MySQL to student table of oracle.

    Here to get all records mysql student table we need to execute

    “select *form Student” only for time without any input values ,

    for this we need to use SimpleStatement object.  To insert the above multiple records in student db table of