3.Java Database Connectivity2

Embed Size (px)

Citation preview

  • 7/29/2019 3.Java Database Connectivity2

    1/27

    Your IT Partner

    Java Database Connectivity

  • 7/29/2019 3.Java Database Connectivity2

    2/27

    CMC Limited

    Object ives contd ..

    Write Java applications to update a database in

    a local or/and remote database

    Write a Java program to execute stored

    procedures in a database Use Java for front-end development

    Understand about JDBC TYPE IV Thin Driver

    using Oracle DB connectivity

  • 7/29/2019 3.Java Database Connectivity2

    3/27

    CMC Limited

    Introduction

    Databases are the tools used to collect and store

    large volumes of data.

    Data is collected and stored in the form of tables

    consisting of rows and columns.

    A DataBase Management System is the softwarewhich enables you to create a database and perform

    operations on the data.

    All database management systems use a structured

    language to perform different kinds of operations ona database.

    Every RDBMS provides some kind of programming

    facility to develop DBMS applications.

  • 7/29/2019 3.Java Database Connectivity2

    4/27

    CMC Limited

    Java Database Connectivity

    JDBC is the software abstraction that interfaces yourJava application with different kinds of databases.

    It sits between your application and the database you

    want to access.

    JDBC provides a set of APIs which is uniform across

    all databases, windowing systems, operating

    systems and hardware environments.

  • 7/29/2019 3.Java Database Connectivity2

    5/27

    CMC Limited

    JDBC Architecture

    A specific RDBMS requires a specific driver. The APIs provided by the JDBC interface layer is

    implemented in the driver.

    The application programmer does not implement any

    of the API.

    JDBC architecture

  • 7/29/2019 3.Java Database Connectivity2

    6/27

    CMC Limited

  • 7/29/2019 3.Java Database Connectivity2

    7/27CMC Limited

    Objectives

    After completing this chapter, the student will be able to:

    Explain JDBC

    Explain JDBC architecture

    Explain JDBC drivers

    Explain Javas support for JDBC

    Write Java programs to make simple queries

    with local or remote databases

    Write Java applications to pass parameters toquery statements from program or/and from the

    user

  • 7/29/2019 3.Java Database Connectivity2

    8/27CMC Limited

    JDBC ODBC Bridge

    Along with JDBC, Sun Microsystems delivers onepiece of software called JDBCODBC bridge.

    JDBC and ODBC are similar in design.

    The JDBC-ODBC bridge enables to access

    databases using ODBC drivers from JDBC. JDBCODBC bridge effectively translate the JDBC

    API calls into the corresponding ODBC calls.

    ODBC drivers are available for almost all types of

    databases.

    With JDBCODBC bridge, JDBC can access almostall databases.

  • 7/29/2019 3.Java Database Connectivity2

    9/27CMC Limited

    Types of JDBC Drivers

    JavaSoft has divided JDBC drivers into fourcategories, based on their construction and the type

    of database they are intended to support.

    These four categories are explained below.

    JDBC-ODBC Bridge Drive Direct Network Connection

    Native API Driver Direct Network Connection

    Network Protocol Driver Indirect Network Connection

    Native Protocol Driver Direct Network Connection

  • 7/29/2019 3.Java Database Connectivity2

    10/27CMC Limited

    Types of JDBC Drivers

    Type 1- This Driver is a JDBC-ODBC bridge that allows Java Program towork with a database using widely available ODBC Driver. The major drawbacks

    of this driver is that it is very slow than other driver and it has to be installed and

    configured on each users machine.

    Type 2- This driver consists of Java classes that work in conjunction with

    the non-java native drivers, provided by the vendors, that has to be installed onthe clients machine. This driver is faster than the Type 1 but it also requires

    installation and configuration.

    Type 3- This driver is a pure Java Network driver (JDBC-Net Driver) that isprovided by some application server and consists of two parts. The first part is

    the Clients part which performs a DBMS independent SQL call and the second

    part is the SQL call itself which is then translated to specific protocol according

    to the middleware vendor.

    Type 4- This driver is a pure Java driver which comes as a .zip or .jar filecontaining Java classes that perform direct calls to the Database Server. It does

    not need any configuration on the clients machine and can be dynamically

    downloaded to the Client.

  • 7/29/2019 3.Java Database Connectivity2

    11/27CMC Limited

    Javas Support for JDBC

    Javas support for JDBC comes from a set ofinterfaces and classes defined in the java.sql

    package.

    These interfaces are listed below.

    Interface CallableStatement Interface Connection

    Interface DatabaseMetaData

    Interface Driver

    Interface PreparedStatement

    Interface ResultSet Interface ResultSetMetaData

    Interface Statement

    Class DriverManager

  • 7/29/2019 3.Java Database Connectivity2

    12/27CMC Limited

    Javas Support for JDBC contd..

    The connection interface is used to establish aconnection to the database you want to access.

    The connection interface defines the following

    methods:

    public void close( ) throws SQLException

    public Statement createStatement() throws

    SQLException ;

    public PreparedStatement prepareStatement()

    throws SQLException;

    The Connection Interface

  • 7/29/2019 3.Java Database Connectivity2

    13/27CMC Limited

    Javas Support for JDBC contd..

    The Statement interface is used to send SQL queries

    to the database and retrieve a set of data.

    SQLstatements can be queries, updates, insertions,

    deletions etc.

    The Statement interface provides a number of

    methods.

    public void close( ) throws SQLException;

    public boolean execute( String sql ) throws

    SQLException;public ResultSet executeQuery(String sql) throws

    SQLException

    public int executeUpdate ( String sql )

    throws SQLException

    The Statement Interface

  • 7/29/2019 3.Java Database Connectivity2

    14/27CMC Limited

    Javas Support for JDBC contd..

    PreparedStatement interface is used to pass parameters into anSQL Statement.

    Since it is extending the Statement interface, all the methods

    available in Statement interface are available to

    PreparedStatement interface.

    In addition, several other methods are available in

    PreparedStatement interface.

    Parameterised Query:-

    String psswd;

    PreparedStatement pstmt=con.prepareStatement("SELECT * FROM

    AdminTable WHERE pwd=?");

    pstmt.setString(1,psswd);

    ResultSet rs=pstmt.executeQuery();

    The PreparedStatement Interface

  • 7/29/2019 3.Java Database Connectivity2

    15/27CMC Limited

    Javas Support for JDBC contd..

    As a result of execution of an SQL statement, one ormore tables of data may be generated.

    The methods in the ResultSet interface can be used

    to retrieve these data.

    public boolean next( ) throws SQLException;

    public String getString(int index) throws

    SQLException;

    public String getString(String column) throws

    SQLException;public Integer getInt(String column) throws

    SQLException;

    The ResultSet Interface

  • 7/29/2019 3.Java Database Connectivity2

    16/27CMC Limited

    Javas Support for JDBC contd..

    Java.sql.ResultSetMetaData class can dynamicallyfind out the structure of the underlying database

    table.

    ResultSet rs = stmt.executeQuery(sqlQuery);

    ResultSetMetaData rsMeta = rs.getMetaData();

    int colCount = rsMeta.getColumnCount();

    for(int i=0; i

  • 7/29/2019 3.Java Database Connectivity2

    17/27CMC Limited

    Javas Support for JDBC contd..

    Another option to create a ResultSet is with Scrollable feature., so that thecursor can be moved forward as well as backward.

    A two version of the createStatement() method exists which gives us this facility.

    The first argument is the type of Scrolling(TYPE_FORWARD_ONLY,TYPE_SCROLL_INSENSITIVE, TYPE_SCROLL_SENSITIVE)

    The second argument is used to make the ResultSet read-only or

    Updateable

    (CONCUR_READ_ONLY or CONCUR_UPDATABLE)

    TYPE_FORWARD: moves the cursor forward only

    TYPE_SCROLL_INSENSITIVE: Scrolling will not reflect the changes that might have

    been done to the result-set.

    TYPE_SCROLL_SENSITIVE: Scrolling should reflect the changes that might have

    been done to the result-set.

    CONCUR_READ_ONLY: open result-set in read-only mode.CONCUR_UPDATABLE: open result-set in updateable mode on cursors current

    position

    ScrollableResultSet

    J S t f JDBC td

  • 7/29/2019 3.Java Database Connectivity2

    18/27CMC Limited

    Javas Support for JDBC contd..

    Ex1.Statement smt =

    con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,

    ResultSet.CONCUR_READ_ONLY);

    ResultSet rs = smt.executeQuery(select * from emp);

    Ex2.

    rs.afterLast();

    while(rs.previous()){

    int id = rs.getInt();

    }

    rs.absolute(25) // moves the cursor to the 25th row;

    rs.first();

    rs.last();

    rs.updateString(name,Tango Charlie);

    rs.updateRow();

    // CONCUR_UPDATABLE option makes the Result Set updateable and This

    line will update the name of the user on the cursors current position.

    Scrollable Result Set contd

    J S t f JDBC td

  • 7/29/2019 3.Java Database Connectivity2

    19/27CMC Limited

    Javas Support for JDBC contd..

    CallableStatement interface extendsPreparedStatement interface.

    CallableStatement interface can be used to execute

    stored SQL procedures in a database.

    These procedures may be taking some input

    parameters and giving some output values.

    The CallableStatement Interface

    J S t f JDBC td

  • 7/29/2019 3.Java Database Connectivity2

    20/27

    CMC Limited

    Javas Support for JDBC contd..

    Driver interface provides methods for establishingconnections with specific databases.

    Such methods use a URL type string as parameter to

    locate and access databases.

    This URL string should have the following

    characteristics:

    It should specify the type of database being

    accessed

    It should contain database access information like

    host name, database name, port number,username, password etc.

    The Driver Interface

    J S t f JDBC td

  • 7/29/2019 3.Java Database Connectivity2

    21/27

    CMC Limited

    Javas Support for JDBC contd..

    The DriverManager class controls the loading ofdriver specific classes.

    Drivers are implemented as a set of .class files.

    Drivers are registered with the DriverManager class.

    Connection con = DriverManager.getConnection("jdbc:odbc:practice");

    The DriverManager Class

  • 7/29/2019 3.Java Database Connectivity2

    22/27

    CMC Limited

    import java.sql.*;

    class JDBCSample

    {

    public static void main(String [] ar)

    {

    try{

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // It load JDBC Driver into memory

    }catch(ClassNotFoundException e)

    {

    System.out.println("The Exception Massage is:"+e);

    }try

    {

    Connection con = DriverManager.getConnection("jdbc:odbc:practice"); // Establishment of Connection

    Statement stmt = con.createStatement(); // Helps to get Statement type of objectResultSet rs = stmt.executeQuery("select * from login"); // Executing Query

    while(rs.next())

    {

    System.out.println(rs.getString("uid"));

    System.out.println(rs.getString("pwd"));

    }

    rs.close();

    stmt.close();

    con.close();} catch(SQLException e)

    {

    System.out.println("The SQL Exception is:"+e);

    }

    }

    }

    An Example

    JDBC E l td

  • 7/29/2019 3.Java Database Connectivity2

    23/27

    CMC Limited

    2nd Example of executeQuery()import java.sql.*;

    class JDBC2

    {

    public static void main(String [] ar)

    {

    try{

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // It load JDBC Driver into memory

    }catch(ClassNotFoundException e)

    {

    System.out.println("The Exception Massage is:"+e);

    }try

    {

    Connection con = DriverManager.getConnection("jdbc:odbc:testing"); // Establishment ofConnection

    Statement stmt = con.createStatement(); // Helps to get Statement type of object

    boolean b = stmt.execute("select * from login"); // Executing Query

    if(b)

    {

    System.out.println("uname");

    System.out.println("pwd");

    }

    stmt.close();

    con.close();

    } catch(SQLException e)

    {

    System.out.println("The SQL Exception is:"+e);

    }

    }

    }

    JDBC Examples con td..

    JDBC E l td

  • 7/29/2019 3.Java Database Connectivity2

    24/27

    CMC Limited

    3rd Example of executeUpdate()JDBC Examples con td..

    import java.sql.*;

    class JDBC3

    {

    public static void main(String [] ar)

    {

    try{

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // It load JDBC Driver into memory

    }catch(ClassNotFoundException e){}

    try

    {

    String uname1="tango";

    String pwd1="charlie";

    Connection con = DriverManager.getConnection("jdbc:odbc:testing"); // Establishment of ConnectionStatement stmt = con.createStatement(); // Helps to get Statement type of object

    String query="INSERT INTO login"+"(uname,pwd)"+"VALUES ('"+uname1+"','"+pwd1+"')";

    int rowEffected = stmt.executeUpdate(query); // Executing Query

    if(rowEffected>0)

    {

    System.out.println(Success!!!);

    }

    stmt.close();

    con.close();

    } catch(SQLException e){}

    }

    }

    JDBC E l td

  • 7/29/2019 3.Java Database Connectivity2

    25/27

    CMC Limited

    4th Example of PreparedStatementJDBC Examples con td..

    import java.sql.*;

    class JDBC4

    {

    //Same as previous example

    String pwd1="charlie";

    Connection con = DriverManager.getConnection("jdbc:odbc:testing"); // Establishment of Connection

    PreparedStatement pstmt=con.prepareStatement("SELECT * FROM login WHERE pwd=?");

    pstmt.setString(1,pwd1);

    ResultSet rs=pstmt.executeQuery();

    if(rs.next())

    {

    System.out.println(rs.getString("uid"));

    System.out.println(rs.getString("pwd"));

    }

    pstmt.close();

    con.close();

    } catch(SQLException e)

    {

    System.out.println("The SQL Exception is:"+e);

    }

    }

    }

    JDBC E amples con td

  • 7/29/2019 3.Java Database Connectivity2

    26/27

    CMC Limited

    5th Example of PreparedStatementJDBC Examples con td..

    import java.sql.*;

    class JDBC5

    {

    public static void main(String [] ar)

    { //same as above

    try

    {

    String pwd1="pentium";

    String uid="Karnataka";

    Connection con = DriverManager.getConnection("jdbc:odbc:testing"); // Establishment of Connection

    PreparedStatement pstmt=con.prepareStatement("UPDATE login SET uname=? where pwd=?");

    pstmt.setString(1,uid);

    pstmt.setString(2,pwd1);int i=pstmt.executeUpdate();

    if(i>0)

    System.out.println(i+" no of row(s)effected");

    pstmt.close();

    con.close();

    } catch(SQLException e)

    {

    System.out.println("The SQL Exception is:"+e);

    }

    }

    }

  • 7/29/2019 3.Java Database Connectivity2

    27/27

    CMC Limited

    JDBC and Applets

    Before, Java security restrictions allowed only alimited JDBC access from applets.

    These limitations were:

    Applets run, using applet viewer utility, could

    access only local databases.

    Applets downloaded from an HTTP server could

    not use native code.

    Another security restriction was that an applet can

    establish a network connection only with the

    HTTP server from where the applet wasdownloaded.

    The applet security restrictions did not allow the

    downloading of JDBC classes.