Thursday, 12 July 2012

JDBC Questions and Answers


                        JDBC (java database connectivity)  
                        ===============================

1. What is JDBC ? what are its advantages ?

A. It is an API .The latest version of jdbc api is (3.0).
   The JDBC 3.0 API is divided into two packages:
   (1) java.sql and (2) javax.sql.
   Both packages are included in the J2SE and J2EE platforms.
  
   advantages:
   ---------------
      The JDBC API can be used to interact with multiple data sources in a    distributed, heterogeneous environment.
      It  can connect to any of the database from java language.
      It can switch over to any backend database without changing java code or      by minute changes.

2. How many JDBC Drivers are there ? what are they?
A. There are 4 types of JDBC drivers.
   a. JDBC-ODBC Bridge Driver(Type-1 driver)
   b. Native API Partly Java Driver(Type-2 driver)
   c. Net protocol pure Java Driver(Type-3 driver)
   d. Native protocol Pure Java Driver(Type-4 driver)

3. Explain about JDBC-ODBC driver(Type-1) ? When this type of driver is used ?
A. In this mechanism the flow of execution will be
  
   Java code(JDBC API)<------>JDBC-ODBC bridge driver<------->ODBC API<-------      >ODBC Layer<-------->DataBase

   This type of JDBC Drivers provides a bridge between JDBC API and ODBC API.
   This Bridge(JDBC-ODBC bridge)translates standard JDBC calls to Corresponding                  
   ODBC Calls, and send them to ODBC database via ODBC Libraries.

   The JDBC API is based on ODBC API.
   ODBC(Open Database Connectivity)is Microsoft's API for Database drivers.
   ODBC is based on X/Open Call Level Interface(CLI)specification for database 
   access.

   The URL and class to be loaded for this type of driver are

   Class :- sun.jdbc.odbc.JdbcOdbcDriver
   URL      :- jdbc:odbc:dsnname

4. Explain about Type-2 driver ? When this type of driver is used ?

A. The Drivers which are written in Native code will come into this category
   In this mechanism the flow of Execution will be
  
   java code(JDBC API)<------>Type-2 driver(jdbc driver)<------->Native
   API(vendor specific)<------->DataBase


   When database call is made using JDBC,the driver translates the request into vendor-specific API calls.
   The database will process the request and sends the results back through the Native API ,which will
   forward them back to the JDBC driver. The JDBC driver will format the results to conform to the JDBC
   standard and return them to the application.

5. Explain about Type-3 driver ? When this type of driver is used ?
A. In this mechanism the flow of Execution will be
   java code(JDBC API)<------>JDBC driver<------->JDBC driver server<-------->Native driver<------->DataBase

   The Java Client Application sends the calls to the Intermediate data access server(jdbc driver server)
   The middle tier then handles the request using other driver(Type-II or Type-IV drivers) to complete the request.
  
6. Explain about Type-4 driver ? When this type of driver is used ?
A. This is a pure java driver(alternative to Type-II drivers).
   In this mechanism the flow of Execution will be

   java code(JDBC API)<------>Type-4 driver(jdbc driver)<------->DataBase
   These type of drivers convert the JDBC API calls to direct network calls using
   vendor specific networking protocol by making direct socket connection with
   database.
   examples of this type of drivers are
   1.Tabular Data Stream for Sybase
   2.Oracle Thin jdbc driver for Oracle

                 
7. What are the Advantages & Disadvantages of Type-2 ,Type-4 Drivers over JDBC-ODBC bridge driver(Type-1)?
A. Type-2 & Type-4 are given

8. Which Driver is preferable for using JDBC API in Applets?
A. Type-4 Drivers.

9.Write the Syntax of URL to get connection ? Explain?
A.Syntax:- jdbc:<subprotocal>:<subname>
   jdbc -----> is a protocol .This is only allowed protocal in JDBC.
   <subprotocal> ----> The subprotocal is used to identify a database driver,or the
   name of the database connectivity mechanism, choosen by the database driver providers.

   <subname>  ------->  The syntax of the subname is driver specific. The driver may choose any
   syntax appropriate for its implementation

   ex: jdbc:odbc:dsn
       jdbc:oracle:oci8:@ database name.
       jdbc:orale:thin:@ database name:port number:SID

10.How do u Load a driver ?
A. Using Driver Class.forName(java.lang.String driverclass) or registerDriver(Driver driver) .

11.what are the types of resultsets in JDBC3.0 ?How you can retrieve information of resultset?
A. ScrollableResultSet and ResultSet.We can retrieve information of resultset by using java.sql.ResultSetMetaData interface.You can get the instance by calling the method getMetaData() on ResulSet object.

12.write the steps to Connect database?
A. Class.forName(The class name of a specific driver);


B. Connection c=DriverManager.getConnection(url of a specific driver,user name,password);
  
   Statement s=c.createStatement();
               (or)
   PreparedStatement p=c.prepareStatement();
               (or)
   CallableStatement cal=c.prpareCall();

   Depending upon the requirement.

13.Can java objects be stored in database? how?
A.Yes.We can store java objects, BY using setObject(),setBlob() and setClob() methods in Prepared Statement

14.what do u mean by isolation level?
A. Isolation means that the business logic can proceed without
   consideration for the other activities of the system.

15.How do u set the isolation level?
A. By using setTransactionIsolation(int level) in java.sql.Connection interface.

   level MEANS:-

    static final int TRANSACTION_READ_UNCOMMITTED //cannot prevent any reads.
    static final int TRANSACTION_READ_COMMITTED   //prevents dirty reads
    static final int TRANSACTION_REPEATABLE_READ  //prevents dirty reads & non-repeatable read.
    static final int TRANSACTION_SERIALIZABLE     //prevents dirty reads , non-repeatable read & phantom read.

    These are the static final fields in java.sql.Connection interface.

16. what is a dirty read?
A.  A Dirty read allows a row changed by one transaction to be
    read by another transaction before any change in the row
    have been committed.

    This problem can be solved by setting the transaction isolation
    level to TRANSACTION_READ_COMMITTED

17. what is a non-repeatable read ?
A.  A non-repeatable read is where one transaction reads a row, a second
    transaction alters or deletes the row, and the first transaction
    re-reads the row, getting different values the second time.

    This problem can be solved by setting the transaction isolation
    level to TRANSACTION_REPEATABLE_READ

18. what is phantom read?
A. A phantom read is where one transaction reads all rows that satisfy
   a WHERE condition, a second transaction inserts a row that satisfies
   that WHERE condition, and the first transaction re-reads for the same
   condition, retrieving the additional 'phantom' row in the second read

   This problem can be solved by setting the transaction isolation
   level to TRANSACTION_SERIALIZABLE


19.What is the difference between java.sql.Statement &
   java.sql.PreparedStatement ?
   write the appropriate situations to use  these statements?
A.

20.How to retrieve the information about the database ?
A.we can retrieve the info about the database by using inerface
  java.sql.DatabaseMetaData

  we can get this object by using getMetaData() method in
  Connection interface.

21.what are the Different types of exceptions in jdbc?
A. BatchUpdateException
   DataTruncation
   SQLException
   SQLWarning

22.How to execute no of queries at one go?
A. By using a batchUpdate's (ie throw addBAtch() and executeBatch())
   in java.sql.Statement interface,or by using procedures.

23. what are the advantages of connection pool.
A. Performance

24.In which interface the methods commit() & rollback() are defined ?
A.java.sql.Connection interface

25.How to store images in database?
A. Using binary streams (ie getBinaryStream() ,setBinaryStream()).But it is not visable in database ,it is stored in form of bytes ,to make it visable we have to use any one frontend tool.

26.How to check null value in JDBC?
A. By using the method wasNull() in ResultSet ,it returns boolean value.
   Returns whether the last column read had a value of SQL NULL.
   Note that you must first call one of the getXXX methods on a column to try to read its value and then call the method wasNull to see if the value read was SQL NULL.

27.Give one Example of static Synchronized method in JDBC API?
A. getConnection() method in DriverManager class.Which is used to get object of Connection interface.

28.What is a Connection?
A. Connection is an interface which is used to make a connection between client and Database (ie opening a session with a particular database).

29.what is the difference between execute() ,executeUpdate() and executeQuery() ? where we will use them?
A. execute() method returns a boolean value (ie if the given query
   returns a resutset then it returns true else false),so depending upon
   the return value we can get the ResultSet object (getResultset())or 
   we can know how many rows have bean affected by our query
   (getUpdateCount()).That is we can use this method for Fetching
   queries and Non-Fetching queries.
  
   Fetching queries are the queries which are used to fetch the records from database (ie which returns resutset)
   ex: Select * from emp.
  
   Non-Fetching queries are the queries which are used to update,insert,create or delete the records from database
   ex: update emp set sal=10000 where empno=7809.

   executeUpdate() method is used for nonfetching queries.which returns int value.

   executeQuery() method is used for fetching queries which returns ResulSet object ,Which contains methods to fetch the values.

30.How is jndi useful for Database connection?
A.


                  JNDI (java naming directory interface)
                  ======================================
1. what are the uses of jndi?
A. The role of the JNDI API in the J2EE platform is two fold.
 
  a) It provides the means to perform standard operations
     to a directory service resource such as LDAP (Lightweight Directory Access Protocal),Novell Directory Sevices, or Netscape Directory Services.

  b) A J2EE applicatin utilizes JNDI to look up interfaces used to create,amongst other things,EJBs,and JDBC connection.


2. How vendor Naming registry supports JNDI?
A.

                  JMS (JAVA MESSAGING SERVICE)
                  ============================
1. What is JMS ?
A. JMS (JAVA MESSAGING SERVICE) is an API .It is a specification with one
    package javax.jms .It is a technology which can pass the information
    synchronously or asynchronously .

2. On what technology is JMS based ?
A. JMS is based on Message-Oriented MiddleWare (MOM).

3. What was the technology for messaging services before JMS was released?
A. Before JMS API specification was released by javasoft ,there was
   IBM's MQSeries implementation of MOM (Message-Oriented MiddleWare).
  
4. What is MOM (Message-Oriented MiddleWare) ?
A. MOM is a software infrastructure that asynchronously connects multiple
   system's through the production and consumption of data message.

5. How many types of data passing does JMS specification allows ?What are they?
A. JMS specification allows two types of data passing.
   a)publish/subscribe [pub/sub model]
   b)point-to-point    [p-t-p model]

6. In real time which type of data passing is used ?
A. Mostly in real time applications we use both types of data passing combinedly.

7. How jndi is used in JMS ?
A. While writing JMS application (pub/sub or p-t-p) we need TopicConnection or
    QueueConnection . we use jndi to get this connections .





8. Write the steps to write pub/sub model application ?
A.
   steps to write Publisher (sender) application :-
   -----------------------------------------------
    a)We have to get the TopicConnection through jndi.
    b)Create TopicSession by invoking a method createTopicSession() .
    c)create a Topic object by invoking createTopic() on TopicSession interface.
    d)create a TopicPublisher object of a Topic by invoking createPublisher(javax.jms.Topic t)
      on TopicSession.(t is a Topic object that specifies the Topic we want to subscribe to).
    e)create TextMessage object and set the text to be published .
    f)publish the message by using a method publish() in Publisher interface .

   steps to write subscriber (receiver) application :-
   --------------------------------------------------
    a)We have to get the TopicConnection through jndi.
    b)Create TopicSession by invoking a method createTopicSession() .
    c)create a Topic object by invoking createTopic() on TopicSession interface.
    d)create a TopicSubscriber object of a Topic by invoking createSubscriber(javax.jms.Topic) or
      createDurableSubscriber(javax.jms.Topic t,String name,String messageselector,boolean nolocal) on TopicSession.
     
      t           ------> is a Topic object that specifies the Topic we want to subscribe to.
      name           ---> is a String that indicates the name under which to maintain the Durable Subscribtion to the specified topic.
      messageselector --> is a String that defines selection criteria.
      nolocal    -------> is a boolean if it is true the Subscriber will not recive messages that were published by the client application .

9. What is the difference between DurableSubscription and non-DurableSubscription ?
A. 
   DurableSubscription :-
   -------------------
     DurableSubscription indicates that the client wants to recive all the messages published to a topic,
     including messages published when the client connection is not active.


   Non-DurableSubscription :-
   -----------------------
     Non-DurableSubscription will not receive the messages published when the client connection is not active.

10. Write the steps to write p-to-p model application ?
A.
   steps to write Sender application :-
   ---------------------------------
    a)We have to get the QueueConnection through jndi.
    b)Create QueueSession by invoking a method createQueueSession() .
    c)Create a Queue object by invoking createQueue() on QueueSession interface.
    d)Create a QueueSender object of a Queue by invoking createSender(javax.jms.Queue q)
      on QueueSession.
    e)Create TextMessage object and set the text to be send .
    f)Send the message by using a method send() .    

   steps to write Receiver application :-
   ------------------------------------
    a)We have to get the QueueConnection through jndi.
    b)Create QueueSession by invoking a method createQueueSession() .
    c)Create a Queue object by invoking createQueue() on QueueSession interface.
    d)Create a QueueReceiver object of a Queue by invoking createReceiver(javax.jms.Queue) on QueueSession.


                  JTA (JAVA TRANSACTION API)
                  ==========================
1. what is JTS?
A. JTS (JAVA TRANSACTION SERVICE) is the java implementation of CORBA's
   OTS (OBJECT TRANSACTION SERVICE).

2. what is JTA ?
A. JTA (JAVA TRANSACTION API) is the API released by javasoft under J2EE.
   It was released after the release of JTS .

3. what are the advantages of JTA over JTS?
A. JTA (JAVA TRANSACTION API) is more flexible and simple to use by the
   programer .The JTA API is divided into two parts
   a)high-level X/Open Call Level Interface(CLI)
   b)low-level XA Call Level Interface(CLI)

   As a programmer using JTA he has to concentrate on high-level x/open
   interface .The low-level XA operations are taken care by the server
   which is giving the implementation to JTA API.
   The user will never perform XA operations directly.This makes the user
   more simple to manipulate with transactions.

4. How JTA or JTS is used by client ?
A. client uses UserTransaction interface in both the cases(JTA/JTS).

No comments:

Post a Comment

Write your openion about my blog spot..To get automatic facebook updates like my Pagehttps://www.facebook.com/shivashankar4u ..It takes only 1 min to write the comment and to like the page.. Thanks.