Parag’s Den

Dedicated to my adored friends…..

Archive for April, 2009

JDBC Driver Types

Posted by paragdongre on April 16, 2009

JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:

Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)

4 types of jdbc drivers are elaborated in detail as shown below:

Type 1: JDBC-ODBC Bridge driver

The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available.


The JDBC-ODBC Bridge allows access to almost any database, since the database’s ODBC drivers are already available.

1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.

Type 2: Native-API/partly Java driver

The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into database-specific calls i.e. this driver is specific to a particular database. Some distinctive characteristic of type 2 jdbc drivers are shown below. Example: Oracle will have oracle native api.

The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type
1 and also it uses Native api which is Database specific.

1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.
3. If we change the Database we have to change the native api as it is specific to a database
4. Mostly obsolete now
5. Usually not thread safe.

Type 3: All Java/Net-protocol driver

Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates the request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.


1. This driver is server-based, so there is no need for any vendor database library to be present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast to load.
5. The type 3 driver typically provides support for features such as caching (connections, query results, and so on), load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.

It requires another server application to install and maintain. Traversing the recordset may take longer, since the data comes through the backend server

Type 4: All Java/Native-protocol driver

The Type 4 uses java networking libraries to communicate directly with the database server.


1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve platform independence and eliminate deployment administration issues. It is most suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don’t have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good.
3. You don’t need to install special software on the client or server. Further, these drivers can be downloaded dynamically.

With type 4 drivers, the user needs a different driver for each database.

Posted in - Java | 1 Comment »

Java Database Connectivity

Posted by paragdongre on April 16, 2009

The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database
applications in Java by making database connections. Using JDBC you can send SQL, PL/SQL
statements to almost any relational database. JDBC is a Java API for executing SQL statements
and supports basic SQL functionality. It provides RDBMS access by allowing you to embed SQL
inside Java code. Because Java can run on a thin client, applets embedded in Web pages can
contain downloadable JDBC code to enable remote database access. You will learn how to
create a table, insert values into it, query the table, retrieve results, and update the table with
the help of a JDBC Program example.

Although JDBC was designed specifically to provide a Java interface to relational databases,
you may find that you need to write Java code to access non-relational databases as well.

JDBC Architecture
Java application calls the JDBC library. JDBC loads a driver which talks to the database.
We can change database engines without changing database code.

Java Database Connectivity Steps
Before you can create a java jdbc connection to the database, you must first import the
java.sql package.
import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are
to be imported.

1. Loading a database driver,
In this step of the jdbc connection process, we load the driver class by calling Class.forName()
with the Driver class name as an argument. Once loaded, the Driver class creates an instance
of itself. A client can connect to Database Server through JDBC Driver. Since most of the
Database servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used.
The return type of the Class.forName (String ClassName) method is “Class”. Class is a class in
java.lang package.
try {
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); //Or any other driver
catch(Exception x){
System.out.println( “Unable to load the driver class!” );

2. Creating a oracle jdbc Connection

The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class manages
the JDBC drivers that are installed on the system. Its getConnection() method is used to establish
a connection to a database. It uses a username, password, and a jdbc url to establish a connection
to the database and returns a connection object. A jdbc Connection represents a session/connection
with a specific database. Within the context of a Connection, SQL, PL/SQL statements are executed
and results are returned. An application can have one or more connections with a single database,
or it can have many connections with different databases. A Connection object provides metadata i.e. information about the database, tables, and fields. It also contains methods to deal with transactions.
JDBC URL Syntax:: jdbc: :

JDBC URL Example:: jdbc: : •Each driver has its own subprotocol
•Each subprotocol has its own syntax for the source. We’re using the jdbc odbc subprotocol, so the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver.
Connection dbConnection=DriverManager.getConnection(url,”loginName”,”Password”)
catch( SQLException x ){
System.out.println( “Couldn’t get connection!” );

3. Creating a jdbc Statement object
Once a connection is obtained we can interact with the database. Connection interface defines
methods for interacting with the database via the established connection. To execute SQL
statements, you need to instantiate a Statement object from your connection object by using the createStatement() method.
Statement statement = dbConnection.createStatement();
A statement object is used to send and execute SQL statements to a database.
Three kinds of Statements
Statement: Execute simple sql queries without parameters.
Statement createStatement()
Creates an SQL Statement object.
Prepared Statement: Execute precompiled sql queries with or without parameters.
PreparedStatement prepareStatement(String sql)
returns a new PreparedStatement object. PreparedStatement objects are precompiled
SQL statements.
Callable Statement: Execute a call to a database stored procedure.
CallableStatement prepareCall(String sql)
returns a new CallableStatement object. CallableStatement objects are SQL stored procedure
call statements.

4. Executing a SQL statement with the Statement object, and returning a jdbc resultSet.

Statement interface defines methods that are used to interact with database via the execution
of SQL statements. The Statement class has three methods for executing statements:
executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to use is executeQuery . For statements that create or modify tables, the method to use is executeUpdate. Note: Statements that create a table, alter a table, or drop a table are all examples of DDL
statements and are executed with the method executeUpdate. execute() executes an SQL
statement that is written as String object.
ResultSet provides access to a table of data generated by executing a Statement. The table
rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current
row of data. The next() method is used to successively step through the rows of the tabular results.
ResultSetMetaData Interface holds information on the types and properties of the columns in
a ResultSet. It is constructed from the Connection object.

Test JDBC Driver Installation

import javax.swing.JOptionPane;

public class TestJDBCDriverInstallation_Oracle {

public static void main(String[] args) {
StringBuffer output = new StringBuffer();
output.append(“Testing oracle driver installation \n”);
try {
String className = “sun.jdbc.odbc.JdbcOdbcDriver”;
Class driverObject = Class.forName(className);
output.append(“Driver : “+driverObject+”\n”);
output.append(“Driver Installation Successful”);
JOptionPane.showMessageDialog(null, output);
} catch (Exception e) {
output = new StringBuffer();
output.append(“Driver Installation FAILED\n”);
JOptionPane.showMessageDialog(null, output);
System.out.println(“Failed: Driver Error: ” + e.getMessage());

Java JDBC Connection Example, JDBC Driver Example

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCDriverInformation {
static String userid=”scott”, password = “tiger”;
static String url = “jdbc:odbc:bob”;
static Connection con = null;
public static void main(String[] args) throws Exception {
Connection con = getOracleJDBCConnection();
if(con!= null){
System.out.println(“Got Connection.”);
DatabaseMetaData meta = con.getMetaData();
System.out.println(“Driver Name : “+meta.getDriverName());
System.out.println(“Driver Version : “+meta.getDriverVersion());

System.out.println(“Could not Get Connection”);

public static Connection getOracleJDBCConnection(){

try {
} catch(java.lang.ClassNotFoundException e) {
System.err.print(“ClassNotFoundException: “);

try {
con = DriverManager.getConnection(url, userid, password);
} catch(SQLException ex) {
System.err.println(“SQLException: ” + ex.getMessage());

return con;


Posted in - Java | Leave a Comment »

Java Basics

Posted by paragdongre on April 16, 2009

History of Java
Java was developed by a team led by James Gosling at Sun Microsystems , a company best known by for its workstations. Java was originally called Oak and designed for use in embedded consumer electronic applications in 1991. It was redesigned for developing Internet application and renamed Java in 1995. Java Program can be embedded in HTML pages and downloaded by Web Browsers to bring live animation and interaction to Web clients.
The power of Java is not limited to web applications. Java is a general purpose programming language. It has full programming features and can be used to develop stand alone applications. Java is inherently object – oriented. Although many object- oriented languages began strictly as procedural languages. Java was designed to be object oriented from the start. Object oriented programming (OOP) is currently popular programming approach that replaces the traditional procedural programming technique.
Characteristics of Java
At the designed time of Java three main objective are taken into consideration viz. Portability (Platform Independent) , Architecture Neutral (Hardware Configuration of Machine), Security of programming codes. But apart from the these main character Java has so many another character. They are as follows.
A) Simple
B) Secure
C) Portable
D) Object-Oriented
E) Robust
F) Multithreaded
G) Architectural Neutral
H) Interpreted
I) High Performance
J) Distributed
K) Dynamic

    Simple :

No one language is Simple to learn but Java is bit easier compared to the popular Object Oriented Programming language like C++. Actually Java is partially modeled after C++ means it uses C++ programming syntax and object oriented features. But Java is great simplified and improved. For instance Pointers and Multiple Inheritance concepts are eliminated from Java instead of this simple structure interfaces are introduced. In Java specification we have so many in built packages, classes and method so that we can reuse it without rewriting the codes.
Java uses automatic memory allocation and garbage collection while in C++ we have to require to allocate memory to garbage collection.

    Java is Object Oriented

Object oriented programming models the real world. Everything in the world can be modeled as an object. A circle, A person, A window icon is an object. A Java Program is called object – oriented because programming in Java is centered on creating objects , manipulating objects and making objects working together. Java program is mostly a collection of objects talking to other objects by invoking each other’s methods. Every object is of certain type and that type is defined by a class or an interface. Most Java Program use a collection of objects of many different type.
i)Class : A template that describe the kinds of state and behavior that objects of its type support.
ii)Object: At runtime , when the Java Virtual Machine (JVM) encounters the new keyword , it will use the appropriate class to make an object which is an instance of that class. For Example
Suppose Demo is a class and is define as
Public class Demo
Int a , b; // instance variables
Public void show() // behavior (instance method)
System.out.println(“A: “+a+”B: “+b);
Statement for creating object is:
Demo d = new Demo();
Above statement is defined as with the help new keyword called to the constructor of data type of class Demo and after calling of the constructor initialize the member variable with their default value of their respective data types if not explicitly define and allocate the memory space and reference of this Object are kept into the reference variables d of type Demo . That object will have its own state , and access to all of the behaviors defined by its class.
iii)State (instance variable) : Each object (instance of a class) will have its own unique set of instance variables as defined in the class. The value assigned to an object’s instance variables make up the object’s state.
iv) Behavior(method) : When programmer creates the class he creates the methods for that class. Methods are where the class’ logic is stored. Methods are where the real work gets done. They are where algorithms get executed and data gets manipulated.
In short , An object has a properties and behaviors. Properties are described by using data and behaviors are defined by using methods. Objects are defined by using classes in Java. A class is like a template for the objects. An Object is a concrete realization of a class description.

    Java is distributed:

Distributed computing involves several computers on a network working together. Java is designed to make distributed computing easy because it handles TCP / IP protocols

    Java is interpreted: (Platform Independent)

The java programs are compiled into Machine code called bytecode. This code can be interpreted on any system that provides a Java Virtual Machine. This Bytecode is machine independent and can run on any machine that has a java interpreter. Usually a compiler translates a high level language program to machine code. The code can only run on the native machine. If you want this same program on other machine, the program has to be recompiled on native machine. For instance, if you compile C program in widows, the executable code generated by the compilers can only run on the windows platform.
With Java, you compile the source code once and the bytecode generated by Java compliers can run on any platform. The Java Program does not need to be recompiled on a target machine.

    Java is Robust:

Robust means reliable. Early checking for possible errors (mishandled exceptional conditions) during execution time with the help of object oriented exception handling construct. Java has a runtime exception handling feature to provide programming support for robustness. Java can catch and respond to an exceptional situation so that the program continues its normal execution and terminate gracefully when a runtime error occurs.
It does not support pointers which eliminate the possibility of overwriting memory and corrupting data. Java support automatic memory management by allocating memory to object if scope of object is over it automatically deallocate memory with help of Garbage Collection.

    Java is Secure

This required the elimination of many features of C and C++. Most notably there are no pointers in Java. Java programs cannot access arbitrary addresses in memory. All memory access is handled behind the scenes by the (presumably) trusted runtime environment. Furthermore Java has strong typing. Variables must be declared Casts are strictly limited to casts between types that make sense. Thus cast such as int to a long or a byte to a short can be done but not a long to a boolean or an int to a String.

Java implements a robust exception handling mechanism to deal with both expected and unexpected errors. The worst that an applet can do to a host system is bringing down the runtime environment.
Most importantly Java applets can be executed in an environment that prohibits them from introducing viruses, deleting or modifying files, or otherwise destroying data and crashing the host computer. A Java enabled web browser checks the byte codes of an applet to verify that it doesn’t do anything nasty before it will run the applet.
During runtime JVM only detect bytecode and any other are ignored that’s why there is no possibility of executing any other code. So no virus programs are executed. Hence Java code is bug free.

    Java is Architecture Neutral

The most remarkable feature of Java is that it is architecture neutral (platform independent). You can write one program that runs on any platform with JVM.

    Java is Portable

Java Program can run on any platform without having to be recompiled. In java language there is platform specific features in the Java Language Specification. For ex. In Ada language the largest integer varies on different platform. But in Java, the size of the integer is same on every platform. Having a fixed size for numbers makes the program portable. The Java environment itself is portable to new hardware and operating systems. In fact the Java compiler itself written in Java.

    Java is High Performance

Java byte codes can be compiled on the fly to code that rivals C++ in speed using a “just-in-time compiler.” Several companies are also working on native-machine-architecture compilers for Java. These will produce executable code that does not require a separate interpreter, and that is indistinguishable in speed from C++. The execution of the bytecode is never as fast as a complied language such as C++. Because Java is interpreted, the bytecode is not directly executed by the system. The bytecode is run through the interpreter.
It is certainly possible to write large programs in Java. The HotJava browser, the Java Workshop integrated development environment and the javac compiler are large programs that are written entirely in Java.

    Java is Multithreaded

Multithreading is the capability for a program to perform several tasks simultaneously within a program.
Java is inherently multi-threaded. A single Java program can have many different threads executing independently and continuously. Three Java applets on the same page can run together with each getting equal time from the CPU with very little extra effort on the part of the programmer.
Unfortunately multithreading is so tightly integrated with Java, that it makes Java rather difficult to port to architectures like Windows 3.1 or the PowerMac that don’t natively support preemptive multi-threading.
There is a cost associated with multi-threading. Multi-threading is to Java what pointer arithmetic is to C, that is, a source of devilishly hard to find bugs. Nonetheless, in simple programs it’s possible to leave multi-threading alone and normally be OK.

    Java is Dynamic

Java was designed to adapt to an evolving environment .Java Program carry with them substantial amounts of run time type information that is used to verify and resolve access to objects at run time. This makes it possible to dynamically link code in safe and expedient manner.
For Example : in the circle class you can add a new data property to indicate the color of the circle and a new method to obtain the circumference of the circle. The original client program that uses the Circle class remains the same. Also at runtime , Java loads classes as they are needed.
Java does not have an explicit link phase. Java source code is divided into .java files, roughly one per each class in the program. The compiler compiles these into .class files containing byte code. Each .java file generally produces exactly one .class file.
The compiler searches the current directory and directories specified in the CLASSPATH environment variable to find other classes explicitly referenced by name in each source code file. If the file that is compiled depends on other, non-compiled files the compiler will try to find them and compile them as well. The compiler is quite smart, and can handle circular dependencies as well as methods that are used before they’re declared. It also can determine whether a source code file has changed since the last time it was compiled.
More importantly, classes that were unknown to a program when it was compiled can still be loaded into it at runtime. For example, a web browser can load applets of differing classes that it’s never seen before without recompilation.
Furthermore, Java .class files tend to be quite small, a few kilobytes at most. It is not necessary to link in large runtime libraries to produce a (non-native) executable. Instead the necessary classes are loaded from the user’s CLASSPATH

    Java and Internet Programming (World Wide Web)

Java Program can run on from a Web Browser. Because Java is full blown programming language you can make the program responsive and interactive with the user. Java Program that run from Web page are called Applets.
Applets use a modern graphics user interface including button, text fields , text area , option buttons and so on. Applets can respond to user events such as mouse movements and keystrokes.

    Garbage Collection

There is no need to explicitly allocate or deallocate memory in Java. Memory is allocated as needed, both on the stack and the heap, and reclaimed by the garbage collector when it is no longer needed. There’s no malloc(), free(), or destructor methods.
There are constructors and these do allocate memory on the heap, but this is transparent to the programmer.
Most Java virtual machines use an inefficient, mark and sweep garbage collector.

Posted in - Java | Leave a Comment »

Shutdown your pc with Timer

Posted by paragdongre on April 9, 2009

Here is another trick to shutdown at a specific time, for example you wish to shutdown at 1:45am. Type this in


Type Code: at 1:45 shutdown -s

(Time should put in 24 hrs Format when u want to shutdown ur pc)

Code:shutdown -a

Posted in 3. Fun | Leave a Comment »