Tuesday, 30 September 2014

SQL Data types

SQL offers six categories of data types to store data into tables.

1. Exact Numeric Data types
Data Type Minimum Maximum
bigint -9,223,372,036,854,775,808 9,223,372,036,854,775,807
int -2,147,483,648 2,147,483,647
smallint -32,768 32,767
tinyint 0 255
bit 0 1
decimal -10^38 +1 10^38 -1
numeric -10^38 +1 10^38 -1
money -922,337,203,685,477.5808 +922,337,203,685,477.5807
smallmoney -214,748.3648 +214,748.3647

2. Approximate Numeric Data types
Data Type Minimum Maximum
float -1.79E + 308 1.79E + 308
real -3.40E + 38 3.40E + 38

3. Date and Time Data types
Data Type From To
datetime Jan 1, 1753 Dec 31, 9999
smalldatetime Jan 1, 1900 Jun 6, 2079
date Stores a date like June 9, 2014

time Stores a time of day like 1:30 P.M.


4. Character Data types
Data type Description
char Maximum length of 8,000 characters.( Fixed length non-Unicode characters)
varchar Maximum of 8,000 characters.(Variable-length non-Unicode data).
varchar(max) Maximum length of 231characters, Variable-length non-Unicode data (SQL Server 2005 only).
text Variable-length non-Unicode data with a maximum length of 2,147,483,647 characters.

5. Unicode Character Data types
Data type Description
nchar Maximum length of 4,000 characters.( Fixed length Unicode)
nvarchar Maximum length of 4,000 characters.(Variable length Unicode)
nvarchar(max) Maximum length of 231characters (SQL Server 2005 only).( Variable length Unicode)
ntext Maximum length of 1,073,741,823 characters. ( Variable length Unicode )

6. Binary Data types
Data type Description
binary Maximum length of 8,000 bytes(Fixed-length binary data )
varbinary Maximum length of 8,000 bytes.(Variable length binary data)
varbinary(max) Maximum length of 231 bytes (SQL Server 2005 only). ( Variable length Binary data)
image Maximum length of 2,147,483,647 bytes. ( Variable length Binary Data)





Prevoius                                                 Next                                                 Home

Database tables

Database is a collection of one or more tables. Each table is identified by a name. Table contains records.

Student table
Id FirstName LastName City
1 Murali Krishna Canada
2 Joel Chelli Guntur
3 Naveed Anjum Vijayawada
4 Jaideep Geera Guntur
5 Arjun Krishna Punur

In the above case, Student is the table name, it contains five records(row represent a record). Each record has four fields (Id, FirstName, LastName, City) associated with it. In the above table, Id is the primary key, means it is used to uniquely identify a row in the table.



Prevoius                                                 Next                                                 Home

Monday, 29 September 2014

SQL

SQL stands for Structured Query Language, used to access and manipulate data stored in RDBMS(Relational Database Management Systems). The scope of SQL includes data insert, query, update and delete, schema creation and modification, and data access control. I am not going to discuss about DBMS in detail, I am going to discuss basics of SQL, so you can able to work with jdbc comfortably.




Prevoius                                                 Next                                                 Home

Saturday, 27 September 2014

Three-tier model Of JDBC

In the three-tier model, commands are sent to a "middle tier", usually to the Application server. Application server sends the commands to data source. Data source process the commands and sends the result to Application server. Application server sends the same response to client.


 
Prevoius                                                 Next                                                 Home

Two-tier model Of JDBC

In two tier model, Java Application communicates directly to the data source. User commands are delivered to the database using JDBC driver and results of those commands are sent back to the user. It is not necessary that both Java application and data source in same machine. They can reside anywhere.




The major problem with two-tier model of jdbc is, it is fine when concurrent number of users accessing your application are less. But it is problematic, when number of users accessing your application becomes more and more.



Prevoius                                                 Next                                                 Home

JDBC Architecture

The JDBC API supports both two-tier and three-tier processing models for database access.



Prevoius                                                 Next                                                 Home

Types Of JDBC Drivers

JDBC driver is a software that makes the Java Application to interact with database. JDBC drivers are divided into four categories.
  1. JDBC-ODBC bridge
  2. Native-API Driver
  3. Network-Protocol Driver(Middle Ware Driver)
  4. Database-Protocol Driver(Pure Java Driver)
Type1 Driver : JDBC-ODBC bridge
Type1 driver also known as JDBC-ODBC bridge, translates JDBC interface calls to ODBC calls. JDBC-ODBC bridge then calls the ODBC driver of given database. The driver is platform-dependent as it makes use of ODBC which in turn depends on native libraries of the underlying operating system the JVM is running upon.
 
Type 2 Driver - Native-API Driver
Type 2 driver is also known as Native-API driver, is a database driver implementation that uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database.


Type 3 Driver - Network-Protocol Driver(MiddleWare Driver)
Type3 driver sends the JDBC driver calls to intermediate server. The intermediate serever connects to the database.

Type 4 Driver - Database-Protocol Driver(Pure Java Driver)
Type 4 driver written completely in Java, converts JDBC calls directly into a vendor-specific database protocol. 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.


Prevoius                                                 Next                                                 Home

Friday, 26 September 2014

Java program to display date and time

import java.util.*;

public class Today {
    static String getDateTime(){
        int day, month, year;
        int second, minute, hour;
        StringBuilder buf = new StringBuilder();
        GregorianCalendar today = new GregorianCalendar();
 
        day = today.get(Calendar.DAY_OF_MONTH);
        month = today.get(Calendar.MONTH);
        year = today.get(Calendar.YEAR);
 
        second = today.get(Calendar.SECOND);
        minute = today.get(Calendar.MINUTE);
        hour = today.get(Calendar.HOUR);
 
        buf.append("Date :" + day +"-" +month+"-" + year +"\n");
        buf.append("Time :" + hour +"-"+minute+"-"+second);
        
        return buf.toString();
    }
    
    public static void main(String args[]){
        System.out.println(getDateTime());
    }
}

Sample Output
Date :26-8-2014
Time :10-14-57



Previous                                                    Next                                                    Home

What is a JDBC driver?

JDBC API defines the interfaces and classes that Java programs use to connect to database and send queries. Where as JDBC driver implements these interfaces and classes for a particular DBMS vendor like Oracle,, DB2, mysql.

For Example you can download the jdbc driver for mysql from

Who Provides JDBC Drivers ?
Usually database vendors (IBM(DB2),Oracle, Sybase) provides database drivers specific to their databases.



Prevoius                                                 Next                                                 Home

sendRedirect() vs forward in servlet

void sendRedirect(java.lang.String location)
This method declared in HttpServletResponse interface. It redirects the client request to some other URL(location) for further processing. It uses a browser redirect. It sends an http response with code 301, and then the browser makes another request to the new page. So we can able to see the redirected address in address bar.

Go through below link for detailed example.

forward( ServletRequest request, ServletResponse response )
This method is declared in RequestDispatcher Interface. It forward the request from a servlet to another resource in the server. Another resource can be a servlet/jsp/html file. This method must be called before committing any response to client. Calling of this method after committing the response cause IllegalStateException.

Go through below link for detailed example.




                                                             Home

Thursday, 25 September 2014

JDBC

JDBC stands for Java Database Connectivity, and is a platform independent interface between databases and Java. Just like packages awt, swing, and ang, jdbc is also a package, that allows Java programs to access database management systems like MySql, oracle, db2 etc.,

The JDBC API consists of a set of interfaces and classes written in the Java programming language. JDBC is a specification, so a Java program can connect to any Database Management System that provides JDBC driver.

High Level Architecture Of JDBC



As you observe the above figure, java Applications (Servlets, jsp or applets) communicate to database using JDBC API. It is the JDBC API which communicates with the databases like DB2, Oracle, MySQL etc., 



Prevoius                                                 Next                                                 Home

Wednesday, 24 September 2014

Serialization Vs Externalization

  1. Serialization is the process of converting object state into sequence of bytes so that it can be persisted in memory, we can transfer this persisted state of object across network. In case of serialization, the serialization of the object is taken care automatically. Where as in externalization, it is the developer responsibility to what to serialize and what not to serialize.
  2. Object Serialization uses the Serializable and Externalizable interfaces.Where as Externalizable interface extends Serializable.
  1. In case of Serialization, it takes care of serializing all the super classes of this class automatically. Where as in Externalization, it is yours responsibility to serialize super class data.
  2. Serializable interface is a marker interface, where as Externalizable interface is not. It provides two methods, writeExternal and readExternal.
Prevoius                                                 Next                                                 Home

Tuesday, 23 September 2014

ReentrantLock

ReentrantLock is the implementation of Lock interface. ReentrantLock class defines a number of public and protected methods for inspecting the state of the lock. This lock supports a maximum of 2147483647 recursive locks by the same thread. Attempts to exceed this limit result in Error throws from locking methods.

Constructors provided by this class
Constructor Description
public ReentrantLock() Creates an instance of ReentrantLock
public ReentrantLock(boolean fair) Creates an instance of ReentrantLock. This constructor accepts an optional fairness parameter. If fair set to true, under contention, locks favor granting access to the longest-waiting thread.

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.TimeUnit;
import java.lang.Object;

public class Task implements Runnable{
    
   int taskNum;
   static Lock myLock = new ReentrantLock(true);
   
   Task(int taskNum){
       this.taskNum = taskNum;
   }
    
   @Override
   public void run(){
       myLock.lock();
       try {
           System.out.println(taskNum +" Started ");
           try {
               TimeUnit.SECONDS.sleep(1);
           } catch (InterruptedException ex) {
               
           }
           System.out.println(taskNum +" Finished ");
        }
       finally {
          myLock.unlock();
       }
    }
}

public class LockEx {
    public static void main(String args[]){
        int taskNum = 1;
        
        while(taskNum < 50){
            Task task = new Task(taskNum);
            new Thread(task).start();
            taskNum++;
        }
    }
}

Sample Output
1 Started 
1 Finished 
2 Started 
2 Finished 
3 Started 
3 Finished 
4 Started 
4 Finished 
5 Started 
5 Finished 
6 Started 
6 Finished 
…
…
…



Prevoius                                                 Next                                                 Home

Lock interface

Just like synchronized methods and synchronized blocks, Lock provides synchronization mechanism. Lock implementations provide more extensive locking operations than synchronized methods and blocks.

ReentrantLock, ReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock implements Lock interface.

Methods in Lock interface
Method Description
void lock() Acquires the lock. If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired.
void lockInterruptibly() Acquires the lock if it is available and returns immediately. If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happens:


a. The lock is acquired by the current thread; or
b. Some other thread interrupts the current thread, and interruption of lock acquisition is supported.
Condition newCondition() Returns a new Condition instance that is bound to this Lock instance.
boolean tryLock() Acquires the lock only if it is free at the time of invocation. Returns true if the lock was acquired and false otherwise.
boolean tryLock(long time, TimeUnit unit) Acquires the lock if it is free within the given waiting time and the current thread has not been interrupted. Returns true if the lock was acquired and false if the waiting time elapsed before the lock was acquired.
void unlock() Releases the lock.

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.TimeUnit;

public class Task implements Runnable{
    
   int taskNum;
   static Lock myLock = new ReentrantLock();
   
   Task(int taskNum){
       this.taskNum = taskNum;
   }
    
   @Override
   public void run(){
       myLock.lock();
       try {
           System.out.println(taskNum +" Started ");
           try {
               TimeUnit.SECONDS.sleep(1);
           } catch (InterruptedException ex) {
               
           }
           System.out.println(taskNum +" Finished ");
        }
       finally {
          myLock.unlock();
       }
    }
}

public class LockEx {
    public static void main(String args[]){
        int taskNum = 1;
        
        while(taskNum < 50){
            Task task = new Task(taskNum);
            new Thread(task).start();
            taskNum++;
        }
    }
}

Output
1 Started 
1 Finished 
2 Started 
2 Finished 
3 Started 
3 Finished 
4 Started 
4 Finished 
6 Started 
6 Finished 
5 Started 
5 Finished 
…
…
…

Prevoius                                                 Next                                                 Home

java.util.concurrent.locks package

Package provides interfaces and classes for locking and waiting for conditions that is distinct from built-in synchronization and monitors.



Prevoius                                                 Next                                                 Home

Monday, 22 September 2014

Externalization

Object Serialization uses the Serializable and Externalizable interfaces.In case of serialization, the serialization of the object is taken care automatically. Where as in externalization, it is the developr responsibility to what to serialize and what not to serialize.

How serialization happens?
As per javadoc, JVM first checks for the Externalizable interface and If the object supports Externalizable, the writeExternal method is called. If the object does not support Externalizable and does implement Serializable, the object is saved using ObjectOutputStream. When an Externalizable object is reconstructed, an instance is created using the public no-arg constructor, then the readExternal method called. Serializable objects are restored by reading them from an ObjectInputStream.

Externalizable interface provides two methods. The class which implements Externalizable interface, must provide the definition for these methods.

Method Description
readExternal(ObjectInput in) The object implements the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays.
writeExternal(ObjectOutput out) The object implements the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, and arrays.

import java.io.*;

public class Employee implements Externalizable{  
    int id;
    String firstName;
    String lastName;
    
    public Employee(){
        super();
    }
    
    Employee(int id, String firstName, String lastName){
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    @Override
    public void writeExternal(ObjectOutput out) throws IOException{
        out.writeObject(firstName);
        out.writeObject(lastName);
        out.writeInt(id);
    }
    
    @Override
    public void readExternal(ObjectInput in) throws ClassNotFoundException, IOException{
        firstName = (String)in.readObject();
        lastName = (String)in.readObject();
        id = (int)in.readInt();
    }
}

import java.io.*;

public class ExternalizeEx {
    public static void main(String args[]){
        Employee emp = new Employee(1, "Krishna","Arjun");
        Employee newEmp = null;
        
        /* Serialize Employee */
  try {
      FileOutputStream fout = new FileOutputStream("ser.out");
      ObjectOutputStream out = new ObjectOutputStream(fout);
      out.writeObject(emp);
            out.flush();
  } 
        catch (IOException e) {
      System.out.println(e);
      System.exit(1);
  }
        
        /* Deserialize Employee */
        try {
      FileInputStream fin = new FileInputStream("ser.out");
      ObjectInputStream in = new ObjectInputStream(fin);       
      newEmp = (Employee) in.readObject();
  }
  catch (IOException | ClassNotFoundException e) {
      System.out.println(e);
      System.exit(1);
  }
        
        System.out.println("Employee emp details");
        System.out.println(emp.id + " " + emp.firstName + " " + emp.lastName);
        
        System.out.println("New Employee newEmp details");
        System.out.println(newEmp.id + " " + newEmp.firstName +" " + newEmp.lastName);       
        
    }
}

Output
Employee emp details
1 Krishna Arjun
New Employee newEmp details
1 Krishna Arjun


In this example, class Employee implements Externalizable interface which means that Employee object is ready for serialization. Unlike serialization, you must specify what to serialize for Externalization. So when you write the "Employee" object to the OutputStream, the "writeExternal" method is called and the data is persisted. The same applies to "readExternal" method in the Employee object i.e., when you read the "Employee" object from the ObjectInputStream, "readExternal" method is called.

What if the super class of Employee doesn't implement Externalizable interface ?
Lets say there is a class 'EmployeeAddress' which is a super class of Employee, but it don't implement Externalizable interface. To persist the fields in the Employee class the writeExternal and readExternal methods of Employee class are modified to save/restore the super class fields first and then the sub class fields.

public class EmployeeAddress {
    String state, country;
    
    EmployeeAddress(String state, String country){
        this.state = state;
        this.country = country;
    }
    
    public EmployeeAddress(){
        super();
    }
}

import java.io.*;

public class Employee extends EmployeeAddress implements Externalizable{  
    int id;
    String firstName;
    String lastName;
    
    public Employee(){
        super();
    }
    
    Employee(int id, String firstName, String lastName, String st, String con){
        super(st, con);
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    @Override
    public void writeExternal(ObjectOutput out) throws IOException{
        out.writeObject(state);
        out.writeObject(country);
        out.writeObject(firstName);
        out.writeObject(lastName);
        out.writeInt(id);
    }
    
    @Override
    public void readExternal(ObjectInput in) throws ClassNotFoundException, IOException{
        state = (String)in.readObject();
        country = (String)in.readObject();
        firstName = (String)in.readObject();
        lastName = (String)in.readObject();
        id = (int)in.readInt();
    }
}

import java.io.*;

public class ExternalizeEx {
    public static void main(String args[]){
        Employee emp = new Employee(1, "Krishna","Arjun","AP", "India");
        Employee newEmp = null;
        
        /* Serialize Employee */
  try {
      FileOutputStream fout = new FileOutputStream("ser.out");
      ObjectOutputStream out = new ObjectOutputStream(fout);
      out.writeObject(emp);
            out.flush();
  } 
        catch (IOException e) {
      System.out.println(e);
      System.exit(1);
  }
        
        /* Deserialize Employee */
        try {
      FileInputStream fin = new FileInputStream("ser.out");
      ObjectInputStream in = new ObjectInputStream(fin);       
      newEmp = (Employee) in.readObject();
  }
  catch (IOException | ClassNotFoundException e) {
      System.out.println(e);
      System.exit(1);
  }
        
        System.out.println("Employee emp details");
        System.out.print(emp.id + " " + emp.firstName + " " + emp.lastName);
        System.out.println(emp.state +" " + emp.country);
        
        System.out.println("New Employee newEmp details");
        System.out.print(newEmp.id + " " + newEmp.firstName +" " + newEmp.lastName+" ");  
        System.out.println(newEmp.state +" " + newEmp.country);
        
    }
}

Output
Employee emp details
1 Krishna ArjunAP India
New Employee newEmp details
1 Krishna Arjun AP India

What if the super class of Employee also implement Externalizable interface ?
Since super class 'EmployeeAddress' implements Externalizable interface, we need to call the super class writeExternal and readExternal methods in sub class to maintain persistancy.

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class EmployeeAddress  implements Externalizable{
    String state, country;
    
    EmployeeAddress(String state, String country){
        this.state = state;
        this.country = country;
    }
    
    public EmployeeAddress(){
        super();
    }
    
     @Override
    public void writeExternal(ObjectOutput out) throws IOException{
        out.writeObject(state);
        out.writeObject(country);
    }
    
    @Override
    public void readExternal(ObjectInput in) throws ClassNotFoundException, IOException{
        state = (String)in.readObject();
        country = (String)in.readObject();
    }
}

import java.io.*;

public class Employee extends EmployeeAddress implements Externalizable{  
    int id;
    String firstName;
    String lastName;
    
    public Employee(){
        super();
    }
    
    Employee(int id, String firstName, String lastName, String st, String con){
        super(st, con);
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    @Override
    public void writeExternal(ObjectOutput out) throws IOException{
        super.writeExternal(out);
        out.writeObject(firstName);
        out.writeObject(lastName);
        out.writeInt(id);
    }
    
    @Override
    public void readExternal(ObjectInput in) throws ClassNotFoundException, IOException{
        super.readExternal(in);
        firstName = (String)in.readObject();
        lastName = (String)in.readObject();
        id = (int)in.readInt();
    }
}

import java.io.*;

public class ExternalizeEx {
    public static void main(String args[]){
        Employee emp = new Employee(1, "Krishna","Arjun","AP", "India");
        Employee newEmp = null;
        
        /* Serialize Employee */
  try {
      FileOutputStream fout = new FileOutputStream("ser.out");
      ObjectOutputStream out = new ObjectOutputStream(fout);
      out.writeObject(emp);
            out.flush();
  } 
        catch (IOException e) {
      System.out.println(e);
      System.exit(1);
  }
        
        /* Deserialize Employee */
        try {
      FileInputStream fin = new FileInputStream("ser.out");
      ObjectInputStream in = new ObjectInputStream(fin);       
      newEmp = (Employee) in.readObject();
  }
  catch (IOException | ClassNotFoundException e) {
      System.out.println(e);
      System.exit(1);
  }
        
        System.out.println("Employee emp details");
        System.out.print(emp.id + " " + emp.firstName + " " + emp.lastName +" ");
        System.out.println(emp.state +" " + emp.country);
        
        System.out.println("New Employee newEmp details");
        System.out.print(newEmp.id + " " + newEmp.firstName +" " + newEmp.lastName+" ");  
        System.out.println(newEmp.state +" " + newEmp.country);
        
    }
}

output
Employee emp details
1 Krishna Arjun AP India
New Employee newEmp details
1 Krishna Arjun AP India

                                                 Home