SlideShare une entreprise Scribd logo
1  sur  33
Collaborate


Knowledge Byte
    In this section, you will learn about:


         •   Working with Joins
         •   JDBC API
         •   Isolation Levels




 ©NIIT                            Collaborate   Lesson 1C / Slide 1 of 33
Collaborate


Working with Joins
    •    SQL joins in queries are executed using the Statement or PreparedStatement
         objects.
    •    A join is an SQL operation that enables you to specify conditions to retrieve
         data from multiple tables.
    •    Different types of joins that you can use in a Java application are:
           • Inner joins
           • Cross joins
           • Outer joins




 ©NIIT                          Collaborate                  Lesson 1C / Slide 2 of 33
Collaborate


Working with Joins (Contd.)
    •    Inner Join:
           • Combines the rows retrieved from multiple tables on the basis of the
             common columns of the tables.
           • Specifies the condition to join the tables using comparison operators in the
             ON clause of the SELECT statement.
           • Can be created using the following code snippet in a java application:
             String str = "SELECT EmpInfo.EName, EmpInfo.DeptID,
             DeptInfo.DeptName, EmpInfo.EmpDesig FROM EmpInfo INNER JOIN
             DeptInfo ON EmpInfo.DeptID = DeptInfo.DeptID";
             Connection con =
             DriverManager.getConnection("jdbc:odbc:MyDataSource",
             "administrator", "");
             Statement stat = con.createStatement();
             ResultSet rs = stat.executeQuery(str);



 ©NIIT                          Collaborate                    Lesson 1C / Slide 3 of 33
Collaborate


Working with Joins (Contd.)
    •    Cross Join:
           • Includes more than one table without any condition in the ON clause.
           • Is also known as cartesian join.
           • Can be created using the following code snippet in a Java application:
             String str = "SELECT EmpID, EName, DeptName, EmpDesig FROM
             EmpInfo CROSS JOIN DeptInfo";
             Connection con =
             DriverManager.getConnection("jdbc:odbc:MyDataSource",
             "administrator", "");
             Statement stat = con.createStatement();
             ResultSet rs = stat.executeQuery(str);




 ©NIIT                          Collaborate                   Lesson 1C / Slide 4 of 33
Collaborate


Working with Joins (Contd.)
    •    Outer Join:
          • Retrieves all the rows from one table and the matching rows from another.
          • Eliminates the information contained in the row that does not match the
             condition for only one of the tables.
          • Is an extension of equi join.
          • Can be created using the following code snippet in a Java application:
             String str = "SELECT EmpInfo.EmpID, EmpInfo.EName,
             EmpInfo.DeptID, DeptInfo.DeptName FROM EmpInfo LEFT OUTER JOIN
             DeptInfo ON EmpInfo.DeptID = DeptInfo.DeptID";
             Connection con =
             DriverManager.getConnection("jdbc:odbc:MyDataSource",
             "administrator", "");
             Statement stat = con.createStatement();
             ResultSet rs = stat.executeQuery(str);


 ©NIIT                         Collaborate                  Lesson 1C / Slide 5 of 33
Collaborate


JDBC API
    •    JDBC API consists of various interfaces and methods that enable the Java
         application to communicate with a database.
    •    The interfaces defined in the JDBC API are categorized in two packages:
         • The java.sql package
         • The javax.sql package




 ©NIIT                        Collaborate                  Lesson 1C / Slide 6 of 33
Collaborate


JDBC API (Contd.)
    •    The java.sql Package:
          • Is also called the JDBC core API.
          • Provides the following classes and interfaces to access databases from
               Java applications:
                • Statement
                • PreparedStatement
                • CallableStatement
                • Connection
                • ResultSet
                • DatabaseMetaData
                • ResultSetMetaData




 ©NIIT                       Collaborate                 Lesson 1C / Slide 7 of 33
Collaborate


 JDBC API (Contd.)
      •   The Statement Interface
           • The following table lists some methods of the Statement interface:
          Method                                   Description

void close()                  Closes a Statement object and releases all the
                              resources associated with it.
void setMaxRows(int           Specifies the maximum number of rows that a
numRow)                       ResultSet object, generated by a Statement object,
                              can store.
int getMaxRows()              Returns the total number of rows that can be stored in
                              a ResultSet object.
void setQueryTimeOut(int      Specifies the time, in seconds, for which the driver
sec)                          should wait to allow a Statement object to execute.
int getQueryTimeout()         Returns the time, in seconds, for which a driver waits
                              to allow a Statement object to execute.

  ©NIIT                      Collaborate                   Lesson 1C / Slide 8 of 33
Collaborate


  JDBC API (Contd.)
  •      The PreparedStatement Interface
         • The following table lists some methods of the PreparedStatement interface:
                Method                                     Description

void setObject(int index, Object          Sets the Object, obj, as the value for the
obj)                                      parameter corresponding to the index. The index
                                          identifies the placeholder in the SQL statement
                                          for which the value needs to be set.

void setDate(int index, Date              Sets the java.sql.Date value for the parameter
date)                                     corresponding to the index. The java.sql.Date
                                          class represents the SQL DATE value in JDBC.

void setTime(int index, Time              Sets the java.sql.Time value for the parameter
time)                                     corresponding to the index. The java.sql.Time
                                          class represents the SQL TIME value in JDBC.

      ©NIIT                      Collaborate                   Lesson 1C / Slide 9 of 33
Collaborate


 JDBC API (Contd.)
     •    Methods of the PreparedStatement Interface (Contd.)

             Method                                       Description

void setBlob(int index, Blob            Sets the Blob type value for the parameter
blob)                                   corresponding to the index. Binary Large Object
                                        (BLOB) is a datatype that enables you to store
                                        binary objects in a database.


void setClob(int index, Clob            Sets the Clob type value for the parameter
clob)                                   corresponding to the index. Character Large
                                        Objects (CLOB) is a datatype that enables you
                                        to store large data in the character format in a
                                        database.



  ©NIIT                        Collaborate                  Lesson 1C / Slide 10 of 33
Collaborate


 JDBC API (Contd.)
 •      The CallableStatement Interface
        • The following table lists some methods of the CallableStatement interface:
              Method                                     Description

boolean getBoolean(int index)           Returns the boolean value for the JDBC BIT
                                        corresponding to the index passed as a
                                        parameter.
byte getByte(int index)                 Returns the byte value for the JDBC TINYINT
                                        corresponding to the index passed as a
                                        parameter.
int getInt(int index)                   Returns the int value for the JDBC INTEGER
                                        corresponding to the index passed as a
                                        parameter.
String getString(int index)             Returns the String value for the JDBC CHAR,
                                        VARCHAR, or LONGVARCHAR corresponding to the
                                        index passed as a parameter.

     ©NIIT                       Collaborate                 Lesson 1C / Slide 11 of 33
Collaborate


JDBC API (Contd.)
•      The Connection Interface
       • The following table lists some methods of the Connection interface:
             Method                                   Description

boolean isClosed()                   Checks whether or not a connection with a
                                     database is closed.

void setReadOnly(Boolean b)          Sets the read-only mode for the connection.

boolean isReadOnly()                 Checks whether or not a Connection object is
                                     read-only.

void rollback()                      Rolls back the changes made to a database
                                     since the last commit or rollback operation.


    ©NIIT                       Collaborate                  Lesson 1C / Slide 12 of 33
Collaborate


  JDBC API (Contd.)
  •      The ResultSet Interface
         • The following table lists some methods of the ResultSet interface:
           Method                                     Description

Array getArray(int in)          Returns an Array object that contains the value of the
                                column in the current row of the ResultSet object.

Statement getStatement()        Returns the Statement object that has generated the
                                ResultSet object.
int getInt(String               Returns the value in the column, columnName, in the
columnName)                     current row of the ResultSet object as an integer type.

String getString(int            Returns the value of the table column in the current row of
index)                          the ResultSet object as a Java String.

boolean rowUpdated()            Returns a boolean value that specifies whether or not the
                                current row of the ResultSet object has been updated.

      ©NIIT                       Collaborate                  Lesson 1C / Slide 13 of 33
Collaborate


JDBC API (Contd.)
•      The DatabaseMetaData Interface
       • The following table lists some methods of the DatabaseMetaData interface:
              Method                                     Description

Connection getConnection()              Returns the Connection object that has created
                                        the current metadata object.

int getMaxColumnsInTable()              Returns the maximum number of columns a
                                        database table can contain.

int getMaxConnections()                 Returns the maximum number of connections
                                        that can be established with a database.


int getMaxRowSize()                     Returns the maximum bytes that a single row in
                                        a database table can store .


    ©NIIT                       Collaborate                 Lesson 1C / Slide 14 of 33
Collaborate


JDBC API (Contd.)
    •    The methods of the DatabaseMetaData interface: (Contd.)

             Method                                 Description


 boolean supportsGroupBy()           Returns a boolean value that indicates
                                     whether or not the database supports the
                                     GROUP BY clause. The GROUP BY clause groups
                                     the result of a SELECT statement.


 boolean supportsUnion()             Returns a boolean value that indicates
                                     whether or not the database supports the
                                     UNION operator. The UNION operator combines
                                     the results of two SELECT statements.




 ©NIIT                       Collaborate                 Lesson 1C / Slide 15 of 33
Collaborate


JDBC API (Contd.)
•      The ResultSetMetaData Interface
       • The following table lists some methods of the ResultSetMetaData interface:
               Method                                    Description

boolean isCurrency(int                  Returns a boolean value that indicates whether
column)                                 the column stores currency value or not.

boolean                                 Returns a boolean value that indicates whether
isDefinitelyWritable(int                the operations to write and update a column will
column)                                 be successfully executed or not.
boolean isSearchable(int                Returns a boolean value that indicates whether
column)                                 the column can be used in the WHERE clause of an
                                        SQL statement or not.
boolean isSigned(int column)            Returns a boolean value that indicates whether
                                        the value stored in the specified column is a
                                        signed number or not.
    ©NIIT                       Collaborate                 Lesson 1C / Slide 16 of 33
Collaborate


JDBC API (Contd.)
    •    The javax.sql Package:
         • Is also called the JDBC Standard Extension API.
         • Provides classes and interfaces to implement database access from Java
              2 Enterprise Edition (J2EE) applications
         • Contains the DataSource interface.




 ©NIIT                       Collaborate                Lesson 1C / Slide 17 of 33
Collaborate


  JDBC API (Contd.)
      •    The DataSource Interface
            • Enables a Java application to establish a connection with a database.
            • The following table lists the methods of DataSource interface:
            Method                                      Description


Connection getConnection()             Establishes a database connection and returns a
                                       connection object.

Connection getConnection(String        Establishes a database connection after
username, String password)             verifying the username and password passed as
                                       parameters.
int getLoginTimeout()                  Returns the maximum time, in seconds, for
                                       which a data source should wait while
                                       establishing a database connection.

   ©NIIT                       Collaborate                 Lesson 1C / Slide 18 of 33
Collaborate


JDBC API (Contd.)
    •    Methods of the DataSource interface: (Contd.)



              Method                                     Description



  void setLoginTimeout(int                 Sets the maximum time, in seconds, for
  seconds)                                 which a data source should wait while
                                           establishing a database connection.




 ©NIIT                       Collaborate                     Lesson 1C / Slide 19 of 33
Collaborate


Isolation Levels
    •    The transaction isolation levels in JDBC determine whether the concurrently
         running transactions in a database can affect each other or not.
    •    Some common problems that might occur when multiple transactions
         simultaneously access a database are:
           • Dirty reads
           • Non-repeatable reads
           • Phantom reads




 ©NIIT                          Collaborate                  Lesson 1C / Slide 20 of 33
Collaborate


Isolation Levels (Contd.)
    •    The isolation levels enable you to isolate the concurrently running transactions
         so that a transaction cannot affect the result of another transaction.
    •    The Connection interface of the JDBC API provides the following fields as int
         values to set isolation levels:
           • TRANSACTION_READ_UNCOMMITTED
           • TRANSACTION_READ_COMMITTED
           • TRANSACTION_REPEATABLE_READ
           • TRANSACTION_SERIALIZABLE




 ©NIIT                           Collaborate                  Lesson 1C / Slide 21 of 33
Collaborate


Isolation Levels (Contd.)
    •    The Connection interface contains the following methods to retrieve and set
         the value of transaction isolation level for a database:
           • getTransactionIsolationLevel()
           • setTransactionIsolationLevel()
    •    The code snippet to use the getTransactionIsolationLevel() method is:
         Connection con = DriverManager.getConnection
         ("jdbc:odbc:MyDatasource","administrator","");
         int transLevel=getTransactionIsolationLevel();


    •    The code snippet to use the setTransactionIsolationLevel() method is
         Connection con = DriverManager.getConnection
         ("jdbc:odbc:MyDatasource","administrator","");
         int transLevel=getTransactionIsolationLevel();
         con.setTransactionIsolationLevel(TRANSACTION_SERIALIZABLE);


 ©NIIT                          Collaborate                 Lesson 1C / Slide 22 of 33
Collaborate


From the Expert’s Desk

    In this section, you will learn:


         •    Best practices on:
              • Creating Database Access Object
              • Storing Connection Information in a Property File
         •    FAQs on JDBC




 ©NIIT                           Collaborate             Lesson 1C / Slide 23 of 33
Collaborate


Best Practices
Creating a Single Database Access Object
    •    You can create a single class to establish a connection, send SQL statements,
         and retrieve results from a database.
    •    It centralizes the data access logic and any changes to the logic do not
         require rewriting and recompiling all application classes.
    •    For example, you can create a Connect class in your application, all other
         classes of your application can use the Connect class to access the database
         and perform the required operation.
    •    If any changes occur you only need to make changes in the Connect class.




 ©NIIT                        Collaborate                  Lesson 1C / Slide 24 of 33
Collaborate


Best Practices
Creating a Single Database Access Object (Contd.)
    •    The steps to create the Connect class are:

         •    Declare the Connection object, ResultSet object, and an int variable
              in the Connect class as static.
         •    Create a static method connectDb() to obtain database connection.
         •    Create a static method processQuery() that executes SQL queries
              and returns a ResultSet object.
         •    Create a static method processDML() that executes DML commands
              and returns an int that specifies the number of affected rows.




 ©NIIT                        Collaborate                 Lesson 1C / Slide 25 of 33
Collaborate


Best Practices
Storing Connection Information in a Property File
    •    A property file can be used to store the database connection information,
         such as driver name, data source name, username, and password to access
         a database.
    •    You can create a file that Java developers can call in any Java application
         that requires database connection.
    •    If the information specified in a property files changes, you need not change
         the Java application using the property file.
    •    You need to change the information in the property file only. This prevents
         recompilation of the Java applications that use the property file.




 ©NIIT                         Collaborate                  Lesson 1C / Slide 26 of 33
Collaborate


FAQs
    •    Can you use the JDBC-ODBC Bridge driver with applets?

         Yes, you can use JDBC-ODBC bridge driver in applet to access a database.
         However, you need to specify permissions in the Java security policy file to
         allow the applet to load the Driver class. If you do not specify the
         permission, the Java security manager will throw an exception of type
         java.security.AccessControlException. This is because an applet cannot
         access a system resource without the proper permission.




 ©NIIT                        Collaborate                  Lesson 1C / Slide 27 of 33
Collaborate


FAQs (Contd.)
    •    To allow the applet to use the JDBC-ODBC bridge driver, creates a
         .java.policy file in your home directory and adds the following permission
         to the file:
              grant
              {
              permission java.lang.RuntimePermission
              "accessClassInPackage.sun.jdbc.odbc";
              permission java.util.PropertyPermission "file.encoding",
              "read";
              };
         The above entry grants the permission, RuntimePermission, to access the
         sun.jdbc.odbc package that contains the JdbcOdbcDriver class and
         PropertyPermission to read binary files. Now you can use the Applet Viewer
         to test the applet.



 ©NIIT                        Collaborate                 Lesson 1C / Slide 28 of 33
Collaborate


FAQs (Contd.)
    •    Can you scroll through a ResultSet object returned from a stored
         procedure?

         You can scroll a ResultSet object that is returned from a stored procedure,
         if it supports JDBC 2.0 or above.




 ©NIIT                        Collaborate                  Lesson 1C / Slide 29 of 33
Collaborate


FAQs (Contd.)
    •    What are Large Objects (LOBs)? Does JDBC support LOBs?

         LOBs are used to retrieve and update large data, such as images, files, or
         scanned files in the database. JDBC 3.0 supports the use of LOB data type to
         store data in the database. The LOBs data are sent to the database in form
         of Unicode stream. There are two types of LOBs, Binary Large Objects
         (BLOBs) and Character Large Objects (CLOBs). JDBC 3.0 API contains
         methods, such as getBlob(), getClob(),setBlob(), and setClob() to
         retrieve and specify the data stored in LOBs. The advantages of using LOBs
         are:
         a.    LOBs provide random access to data.
         b.    LOBs allow you to search for a pattern in the data.
         c.    LOBs enable you to determine the length of the data before actually
               retrieving the data.



 ©NIIT                        Collaborate                  Lesson 1C / Slide 30 of 33
Collaborate


Challenge
    •    An object of the ________ interface enables a Java application to establish a
         connection with a database.
    •    The ______________ method is used to set the transaction isolation level.
    •    The equi join retrieves data from multiple tables on the basis of the condition
         specified in the WHERE clause. (True/False)
    •    Which one of the following constants sets the database isolation levels to
         prevent dirty reads and non-repeatable reads?
         •    TRANSACTION_READ_UNCOMMITTED
         •    TRANSACTION_READ_COMMITTED
         •    TRANSACTION_REPEATABLE READ
         •    TRANSACTION_SERIALIZABLE




 ©NIIT                         Collaborate                   Lesson 1C / Slide 31 of 33
Collaborate


Challenge (Contd.)
    •    What will be the result of executing the following code snippet?
         Statement sql2 = con.createStatement();
         int result=sql2.executeUpdate("Select * From Publishers");
         •   Will throw an exception
         •   Will result in compilation error
         •   Will return the number of rows retrieved from Publishers table
         •   Will return null




 ©NIIT                       Collaborate                 Lesson 1C / Slide 32 of 33
Collaborate


Solutions to Challenge
    •    Connection
    •    setTransactionIsolationLevel()
    •    True
    •    a. TYPE_SCROLL_SENSITIVE
    •    b. Will result in compilation error




 ©NIIT                        Collaborate      Lesson 1C / Slide 33 of 33

Contenu connexe

Tendances

Ado.net session02
Ado.net session02Ado.net session02
Ado.net session02Niit Care
 
Ado.net session07
Ado.net session07Ado.net session07
Ado.net session07Niit Care
 
Ado.net session04
Ado.net session04Ado.net session04
Ado.net session04Niit Care
 
Ado.net session05
Ado.net session05Ado.net session05
Ado.net session05Niit Care
 
Entity Framework v1 and v2
Entity Framework v1 and v2Entity Framework v1 and v2
Entity Framework v1 and v2Eric Nelson
 
Learn dot net attributes
Learn dot net attributesLearn dot net attributes
Learn dot net attributessonia merchant
 
Java Beans Unit 4(part 2)
Java Beans Unit 4(part 2)Java Beans Unit 4(part 2)
Java Beans Unit 4(part 2)SURBHI SAROHA
 
ORM Concepts and JPA 2.0 Specifications
ORM Concepts and JPA 2.0 SpecificationsORM Concepts and JPA 2.0 Specifications
ORM Concepts and JPA 2.0 SpecificationsAhmed Ramzy
 
Vb.net session 05
Vb.net session 05Vb.net session 05
Vb.net session 05Niit Care
 
Vb net xp_05
Vb net xp_05Vb net xp_05
Vb net xp_05Niit Care
 
Easy Data Object Relational Mapping Tool
Easy Data Object Relational Mapping ToolEasy Data Object Relational Mapping Tool
Easy Data Object Relational Mapping ToolHasitha Guruge
 
Hibernate
HibernateHibernate
HibernateAjay K
 
Visual Basic.Net & Ado.Net
Visual Basic.Net & Ado.NetVisual Basic.Net & Ado.Net
Visual Basic.Net & Ado.NetFaRid Adwa
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate FrameworkRaveendra R
 
Introduction to OO, Java and Eclipse/WebSphere
Introduction to OO, Java and Eclipse/WebSphereIntroduction to OO, Java and Eclipse/WebSphere
Introduction to OO, Java and Eclipse/WebSphereeLink Business Innovations
 

Tendances (20)

Ado.net session02
Ado.net session02Ado.net session02
Ado.net session02
 
Ado.net session07
Ado.net session07Ado.net session07
Ado.net session07
 
Ado.net session04
Ado.net session04Ado.net session04
Ado.net session04
 
Java beans
Java beansJava beans
Java beans
 
Ado.net session05
Ado.net session05Ado.net session05
Ado.net session05
 
Ado.net
Ado.netAdo.net
Ado.net
 
Jpa
JpaJpa
Jpa
 
Entity Framework v1 and v2
Entity Framework v1 and v2Entity Framework v1 and v2
Entity Framework v1 and v2
 
Learn dot net attributes
Learn dot net attributesLearn dot net attributes
Learn dot net attributes
 
Java Beans Unit 4(part 2)
Java Beans Unit 4(part 2)Java Beans Unit 4(part 2)
Java Beans Unit 4(part 2)
 
ORM Concepts and JPA 2.0 Specifications
ORM Concepts and JPA 2.0 SpecificationsORM Concepts and JPA 2.0 Specifications
ORM Concepts and JPA 2.0 Specifications
 
Vb.net session 05
Vb.net session 05Vb.net session 05
Vb.net session 05
 
Vb net xp_05
Vb net xp_05Vb net xp_05
Vb net xp_05
 
Easy Data Object Relational Mapping Tool
Easy Data Object Relational Mapping ToolEasy Data Object Relational Mapping Tool
Easy Data Object Relational Mapping Tool
 
Hibernate
HibernateHibernate
Hibernate
 
Visual Basic.Net & Ado.Net
Visual Basic.Net & Ado.NetVisual Basic.Net & Ado.Net
Visual Basic.Net & Ado.Net
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
Image Converter
Image ConverterImage Converter
Image Converter
 
ASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NETASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NET
 
Introduction to OO, Java and Eclipse/WebSphere
Introduction to OO, Java and Eclipse/WebSphereIntroduction to OO, Java and Eclipse/WebSphere
Introduction to OO, Java and Eclipse/WebSphere
 

En vedette (8)

Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Java session16
Java session16Java session16
Java session16
 
Interface result set
Interface result setInterface result set
Interface result set
 
Jdbc session01
Jdbc session01Jdbc session01
Jdbc session01
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Jdbc 2
Jdbc 2Jdbc 2
Jdbc 2
 

Similaire à JDBC Joins API Isolation

Jdbc session02
Jdbc session02Jdbc session02
Jdbc session02Niit Care
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkBill Lyons
 
Spring db-access mod03
Spring db-access mod03Spring db-access mod03
Spring db-access mod03Guo Albert
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionMazenetsolution
 
Jdbc Lecture5
Jdbc Lecture5Jdbc Lecture5
Jdbc Lecture5phanleson
 
3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivityweb360
 
Dao pattern
Dao patternDao pattern
Dao patternciriako
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityAtul Saurabh
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2Haroon Idrees
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaPawanMM
 
Java session17
Java session17Java session17
Java session17Niit Care
 

Similaire à JDBC Joins API Isolation (20)

Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
 
Data access
Data accessData access
Data access
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc session02
Jdbc session02Jdbc session02
Jdbc session02
 
JDBC
JDBCJDBC
JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLink
 
Spring db-access mod03
Spring db-access mod03Spring db-access mod03
Spring db-access mod03
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
Jdbc Lecture5
Jdbc Lecture5Jdbc Lecture5
Jdbc Lecture5
 
3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivity
 
Dao pattern
Dao patternDao pattern
Dao pattern
 
Assignment#10
Assignment#10Assignment#10
Assignment#10
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
 
Jdbc
Jdbc   Jdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise Java
 
Java session17
Java session17Java session17
Java session17
 

Plus de Niit Care (20)

Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 b
 
Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 b
 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 a
 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 c
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 b
 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 a
 
Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 c
 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 b
 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 a
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 c
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 a
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 c
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 b
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
 
Dacj 1-3 b
Dacj 1-3 bDacj 1-3 b
Dacj 1-3 b
 
Dacj 1-3 a
Dacj 1-3 aDacj 1-3 a
Dacj 1-3 a
 
Dacj 1-2 c
Dacj 1-2 cDacj 1-2 c
Dacj 1-2 c
 
Dacj 1-2 a
Dacj 1-2 aDacj 1-2 a
Dacj 1-2 a
 
Dacj 1-1 c
Dacj 1-1 cDacj 1-1 c
Dacj 1-1 c
 

Dernier

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 

Dernier (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

JDBC Joins API Isolation

  • 1. Collaborate Knowledge Byte In this section, you will learn about: • Working with Joins • JDBC API • Isolation Levels ©NIIT Collaborate Lesson 1C / Slide 1 of 33
  • 2. Collaborate Working with Joins • SQL joins in queries are executed using the Statement or PreparedStatement objects. • A join is an SQL operation that enables you to specify conditions to retrieve data from multiple tables. • Different types of joins that you can use in a Java application are: • Inner joins • Cross joins • Outer joins ©NIIT Collaborate Lesson 1C / Slide 2 of 33
  • 3. Collaborate Working with Joins (Contd.) • Inner Join: • Combines the rows retrieved from multiple tables on the basis of the common columns of the tables. • Specifies the condition to join the tables using comparison operators in the ON clause of the SELECT statement. • Can be created using the following code snippet in a java application: String str = "SELECT EmpInfo.EName, EmpInfo.DeptID, DeptInfo.DeptName, EmpInfo.EmpDesig FROM EmpInfo INNER JOIN DeptInfo ON EmpInfo.DeptID = DeptInfo.DeptID"; Connection con = DriverManager.getConnection("jdbc:odbc:MyDataSource", "administrator", ""); Statement stat = con.createStatement(); ResultSet rs = stat.executeQuery(str); ©NIIT Collaborate Lesson 1C / Slide 3 of 33
  • 4. Collaborate Working with Joins (Contd.) • Cross Join: • Includes more than one table without any condition in the ON clause. • Is also known as cartesian join. • Can be created using the following code snippet in a Java application: String str = "SELECT EmpID, EName, DeptName, EmpDesig FROM EmpInfo CROSS JOIN DeptInfo"; Connection con = DriverManager.getConnection("jdbc:odbc:MyDataSource", "administrator", ""); Statement stat = con.createStatement(); ResultSet rs = stat.executeQuery(str); ©NIIT Collaborate Lesson 1C / Slide 4 of 33
  • 5. Collaborate Working with Joins (Contd.) • Outer Join: • Retrieves all the rows from one table and the matching rows from another. • Eliminates the information contained in the row that does not match the condition for only one of the tables. • Is an extension of equi join. • Can be created using the following code snippet in a Java application: String str = "SELECT EmpInfo.EmpID, EmpInfo.EName, EmpInfo.DeptID, DeptInfo.DeptName FROM EmpInfo LEFT OUTER JOIN DeptInfo ON EmpInfo.DeptID = DeptInfo.DeptID"; Connection con = DriverManager.getConnection("jdbc:odbc:MyDataSource", "administrator", ""); Statement stat = con.createStatement(); ResultSet rs = stat.executeQuery(str); ©NIIT Collaborate Lesson 1C / Slide 5 of 33
  • 6. Collaborate JDBC API • JDBC API consists of various interfaces and methods that enable the Java application to communicate with a database. • The interfaces defined in the JDBC API are categorized in two packages: • The java.sql package • The javax.sql package ©NIIT Collaborate Lesson 1C / Slide 6 of 33
  • 7. Collaborate JDBC API (Contd.) • The java.sql Package: • Is also called the JDBC core API. • Provides the following classes and interfaces to access databases from Java applications: • Statement • PreparedStatement • CallableStatement • Connection • ResultSet • DatabaseMetaData • ResultSetMetaData ©NIIT Collaborate Lesson 1C / Slide 7 of 33
  • 8. Collaborate JDBC API (Contd.) • The Statement Interface • The following table lists some methods of the Statement interface: Method Description void close() Closes a Statement object and releases all the resources associated with it. void setMaxRows(int Specifies the maximum number of rows that a numRow) ResultSet object, generated by a Statement object, can store. int getMaxRows() Returns the total number of rows that can be stored in a ResultSet object. void setQueryTimeOut(int Specifies the time, in seconds, for which the driver sec) should wait to allow a Statement object to execute. int getQueryTimeout() Returns the time, in seconds, for which a driver waits to allow a Statement object to execute. ©NIIT Collaborate Lesson 1C / Slide 8 of 33
  • 9. Collaborate JDBC API (Contd.) • The PreparedStatement Interface • The following table lists some methods of the PreparedStatement interface: Method Description void setObject(int index, Object Sets the Object, obj, as the value for the obj) parameter corresponding to the index. The index identifies the placeholder in the SQL statement for which the value needs to be set. void setDate(int index, Date Sets the java.sql.Date value for the parameter date) corresponding to the index. The java.sql.Date class represents the SQL DATE value in JDBC. void setTime(int index, Time Sets the java.sql.Time value for the parameter time) corresponding to the index. The java.sql.Time class represents the SQL TIME value in JDBC. ©NIIT Collaborate Lesson 1C / Slide 9 of 33
  • 10. Collaborate JDBC API (Contd.) • Methods of the PreparedStatement Interface (Contd.) Method Description void setBlob(int index, Blob Sets the Blob type value for the parameter blob) corresponding to the index. Binary Large Object (BLOB) is a datatype that enables you to store binary objects in a database. void setClob(int index, Clob Sets the Clob type value for the parameter clob) corresponding to the index. Character Large Objects (CLOB) is a datatype that enables you to store large data in the character format in a database. ©NIIT Collaborate Lesson 1C / Slide 10 of 33
  • 11. Collaborate JDBC API (Contd.) • The CallableStatement Interface • The following table lists some methods of the CallableStatement interface: Method Description boolean getBoolean(int index) Returns the boolean value for the JDBC BIT corresponding to the index passed as a parameter. byte getByte(int index) Returns the byte value for the JDBC TINYINT corresponding to the index passed as a parameter. int getInt(int index) Returns the int value for the JDBC INTEGER corresponding to the index passed as a parameter. String getString(int index) Returns the String value for the JDBC CHAR, VARCHAR, or LONGVARCHAR corresponding to the index passed as a parameter. ©NIIT Collaborate Lesson 1C / Slide 11 of 33
  • 12. Collaborate JDBC API (Contd.) • The Connection Interface • The following table lists some methods of the Connection interface: Method Description boolean isClosed() Checks whether or not a connection with a database is closed. void setReadOnly(Boolean b) Sets the read-only mode for the connection. boolean isReadOnly() Checks whether or not a Connection object is read-only. void rollback() Rolls back the changes made to a database since the last commit or rollback operation. ©NIIT Collaborate Lesson 1C / Slide 12 of 33
  • 13. Collaborate JDBC API (Contd.) • The ResultSet Interface • The following table lists some methods of the ResultSet interface: Method Description Array getArray(int in) Returns an Array object that contains the value of the column in the current row of the ResultSet object. Statement getStatement() Returns the Statement object that has generated the ResultSet object. int getInt(String Returns the value in the column, columnName, in the columnName) current row of the ResultSet object as an integer type. String getString(int Returns the value of the table column in the current row of index) the ResultSet object as a Java String. boolean rowUpdated() Returns a boolean value that specifies whether or not the current row of the ResultSet object has been updated. ©NIIT Collaborate Lesson 1C / Slide 13 of 33
  • 14. Collaborate JDBC API (Contd.) • The DatabaseMetaData Interface • The following table lists some methods of the DatabaseMetaData interface: Method Description Connection getConnection() Returns the Connection object that has created the current metadata object. int getMaxColumnsInTable() Returns the maximum number of columns a database table can contain. int getMaxConnections() Returns the maximum number of connections that can be established with a database. int getMaxRowSize() Returns the maximum bytes that a single row in a database table can store . ©NIIT Collaborate Lesson 1C / Slide 14 of 33
  • 15. Collaborate JDBC API (Contd.) • The methods of the DatabaseMetaData interface: (Contd.) Method Description boolean supportsGroupBy() Returns a boolean value that indicates whether or not the database supports the GROUP BY clause. The GROUP BY clause groups the result of a SELECT statement. boolean supportsUnion() Returns a boolean value that indicates whether or not the database supports the UNION operator. The UNION operator combines the results of two SELECT statements. ©NIIT Collaborate Lesson 1C / Slide 15 of 33
  • 16. Collaborate JDBC API (Contd.) • The ResultSetMetaData Interface • The following table lists some methods of the ResultSetMetaData interface: Method Description boolean isCurrency(int Returns a boolean value that indicates whether column) the column stores currency value or not. boolean Returns a boolean value that indicates whether isDefinitelyWritable(int the operations to write and update a column will column) be successfully executed or not. boolean isSearchable(int Returns a boolean value that indicates whether column) the column can be used in the WHERE clause of an SQL statement or not. boolean isSigned(int column) Returns a boolean value that indicates whether the value stored in the specified column is a signed number or not. ©NIIT Collaborate Lesson 1C / Slide 16 of 33
  • 17. Collaborate JDBC API (Contd.) • The javax.sql Package: • Is also called the JDBC Standard Extension API. • Provides classes and interfaces to implement database access from Java 2 Enterprise Edition (J2EE) applications • Contains the DataSource interface. ©NIIT Collaborate Lesson 1C / Slide 17 of 33
  • 18. Collaborate JDBC API (Contd.) • The DataSource Interface • Enables a Java application to establish a connection with a database. • The following table lists the methods of DataSource interface: Method Description Connection getConnection() Establishes a database connection and returns a connection object. Connection getConnection(String Establishes a database connection after username, String password) verifying the username and password passed as parameters. int getLoginTimeout() Returns the maximum time, in seconds, for which a data source should wait while establishing a database connection. ©NIIT Collaborate Lesson 1C / Slide 18 of 33
  • 19. Collaborate JDBC API (Contd.) • Methods of the DataSource interface: (Contd.) Method Description void setLoginTimeout(int Sets the maximum time, in seconds, for seconds) which a data source should wait while establishing a database connection. ©NIIT Collaborate Lesson 1C / Slide 19 of 33
  • 20. Collaborate Isolation Levels • The transaction isolation levels in JDBC determine whether the concurrently running transactions in a database can affect each other or not. • Some common problems that might occur when multiple transactions simultaneously access a database are: • Dirty reads • Non-repeatable reads • Phantom reads ©NIIT Collaborate Lesson 1C / Slide 20 of 33
  • 21. Collaborate Isolation Levels (Contd.) • The isolation levels enable you to isolate the concurrently running transactions so that a transaction cannot affect the result of another transaction. • The Connection interface of the JDBC API provides the following fields as int values to set isolation levels: • TRANSACTION_READ_UNCOMMITTED • TRANSACTION_READ_COMMITTED • TRANSACTION_REPEATABLE_READ • TRANSACTION_SERIALIZABLE ©NIIT Collaborate Lesson 1C / Slide 21 of 33
  • 22. Collaborate Isolation Levels (Contd.) • The Connection interface contains the following methods to retrieve and set the value of transaction isolation level for a database: • getTransactionIsolationLevel() • setTransactionIsolationLevel() • The code snippet to use the getTransactionIsolationLevel() method is: Connection con = DriverManager.getConnection ("jdbc:odbc:MyDatasource","administrator",""); int transLevel=getTransactionIsolationLevel(); • The code snippet to use the setTransactionIsolationLevel() method is Connection con = DriverManager.getConnection ("jdbc:odbc:MyDatasource","administrator",""); int transLevel=getTransactionIsolationLevel(); con.setTransactionIsolationLevel(TRANSACTION_SERIALIZABLE); ©NIIT Collaborate Lesson 1C / Slide 22 of 33
  • 23. Collaborate From the Expert’s Desk In this section, you will learn: • Best practices on: • Creating Database Access Object • Storing Connection Information in a Property File • FAQs on JDBC ©NIIT Collaborate Lesson 1C / Slide 23 of 33
  • 24. Collaborate Best Practices Creating a Single Database Access Object • You can create a single class to establish a connection, send SQL statements, and retrieve results from a database. • It centralizes the data access logic and any changes to the logic do not require rewriting and recompiling all application classes. • For example, you can create a Connect class in your application, all other classes of your application can use the Connect class to access the database and perform the required operation. • If any changes occur you only need to make changes in the Connect class. ©NIIT Collaborate Lesson 1C / Slide 24 of 33
  • 25. Collaborate Best Practices Creating a Single Database Access Object (Contd.) • The steps to create the Connect class are: • Declare the Connection object, ResultSet object, and an int variable in the Connect class as static. • Create a static method connectDb() to obtain database connection. • Create a static method processQuery() that executes SQL queries and returns a ResultSet object. • Create a static method processDML() that executes DML commands and returns an int that specifies the number of affected rows. ©NIIT Collaborate Lesson 1C / Slide 25 of 33
  • 26. Collaborate Best Practices Storing Connection Information in a Property File • A property file can be used to store the database connection information, such as driver name, data source name, username, and password to access a database. • You can create a file that Java developers can call in any Java application that requires database connection. • If the information specified in a property files changes, you need not change the Java application using the property file. • You need to change the information in the property file only. This prevents recompilation of the Java applications that use the property file. ©NIIT Collaborate Lesson 1C / Slide 26 of 33
  • 27. Collaborate FAQs • Can you use the JDBC-ODBC Bridge driver with applets? Yes, you can use JDBC-ODBC bridge driver in applet to access a database. However, you need to specify permissions in the Java security policy file to allow the applet to load the Driver class. If you do not specify the permission, the Java security manager will throw an exception of type java.security.AccessControlException. This is because an applet cannot access a system resource without the proper permission. ©NIIT Collaborate Lesson 1C / Slide 27 of 33
  • 28. Collaborate FAQs (Contd.) • To allow the applet to use the JDBC-ODBC bridge driver, creates a .java.policy file in your home directory and adds the following permission to the file: grant { permission java.lang.RuntimePermission "accessClassInPackage.sun.jdbc.odbc"; permission java.util.PropertyPermission "file.encoding", "read"; }; The above entry grants the permission, RuntimePermission, to access the sun.jdbc.odbc package that contains the JdbcOdbcDriver class and PropertyPermission to read binary files. Now you can use the Applet Viewer to test the applet. ©NIIT Collaborate Lesson 1C / Slide 28 of 33
  • 29. Collaborate FAQs (Contd.) • Can you scroll through a ResultSet object returned from a stored procedure? You can scroll a ResultSet object that is returned from a stored procedure, if it supports JDBC 2.0 or above. ©NIIT Collaborate Lesson 1C / Slide 29 of 33
  • 30. Collaborate FAQs (Contd.) • What are Large Objects (LOBs)? Does JDBC support LOBs? LOBs are used to retrieve and update large data, such as images, files, or scanned files in the database. JDBC 3.0 supports the use of LOB data type to store data in the database. The LOBs data are sent to the database in form of Unicode stream. There are two types of LOBs, Binary Large Objects (BLOBs) and Character Large Objects (CLOBs). JDBC 3.0 API contains methods, such as getBlob(), getClob(),setBlob(), and setClob() to retrieve and specify the data stored in LOBs. The advantages of using LOBs are: a. LOBs provide random access to data. b. LOBs allow you to search for a pattern in the data. c. LOBs enable you to determine the length of the data before actually retrieving the data. ©NIIT Collaborate Lesson 1C / Slide 30 of 33
  • 31. Collaborate Challenge • An object of the ________ interface enables a Java application to establish a connection with a database. • The ______________ method is used to set the transaction isolation level. • The equi join retrieves data from multiple tables on the basis of the condition specified in the WHERE clause. (True/False) • Which one of the following constants sets the database isolation levels to prevent dirty reads and non-repeatable reads? • TRANSACTION_READ_UNCOMMITTED • TRANSACTION_READ_COMMITTED • TRANSACTION_REPEATABLE READ • TRANSACTION_SERIALIZABLE ©NIIT Collaborate Lesson 1C / Slide 31 of 33
  • 32. Collaborate Challenge (Contd.) • What will be the result of executing the following code snippet? Statement sql2 = con.createStatement(); int result=sql2.executeUpdate("Select * From Publishers"); • Will throw an exception • Will result in compilation error • Will return the number of rows retrieved from Publishers table • Will return null ©NIIT Collaborate Lesson 1C / Slide 32 of 33
  • 33. Collaborate Solutions to Challenge • Connection • setTransactionIsolationLevel() • True • a. TYPE_SCROLL_SENSITIVE • b. Will result in compilation error ©NIIT Collaborate Lesson 1C / Slide 33 of 33