Tuesday, 5 June 2012

How to connect Java Application with Oracle Database using JDBC

How to connect Java Application with Oracle Database 10G using JDBC
This example uses an Oracle JDBC driver to connect to an Oracle database instance.


Classpath Settings:
First and foremost make all the JARS(listed below) are configured in your classpath
All the these below jars are available at location: \oracle\product\10.2.0\db_1\jdbc\lib

1. classes12.jar
2. ojdbc14.jar
3. nls_charset12.jar
4. ojdbc14_g.jar
5. ojdbc14dms.jar
6. ojdbc14dms_g.jar
7. classes12.zip
8. classes12dms.zip


Configure these JARS using ECLIPSE































Java Source  Code

JavaFile : DBConnect.java

import java.sql.*;
class DBConnect {
  public static void main (String[] args) throws Exception
  {
   Class.forName ("oracle.jdbc.OracleDriver");

   Connection con = DriverManager.getConnection("jdbc:oracle:thin:@//myname:1521/orcl1", "system", "dblogin");
        // @//machineName:port/SID,   userid,  password
            // myname: system Name(machine Name)
            // port=1521
            // SID=orcl1
            // userid=system
            // password=dblogin
   try {
     Statement stmt = con.createStatement();

                // Create Oracle DatabaseMetaData object
                DatabaseMetaData meta = con.getMetaData();
               
                  // gets driver info:
        System.out.println("JDBC driver version is " + meta.getDriverVersion());
               
     try {
                ResultSet rset = stmt.executeQuery("select BANNER from SYS.V_$VERSION");
              
       try {
         while (rset.next())
           System.out.println (rset.getString(1));   // Print col 1
       }
       finally {
          try { rset.close(); } catch (Exception ignore) {}
       }
     }
     finally {
       try { stmt.close(); } catch (Exception ignore) {}
     }
   }
   finally {
     try { con.close(); } catch (Exception ignore) {}
   }
  }
}

OUTPUT

JDBC driver version is 10.2.0.1.0
Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod
PL/SQL Release 10.2.0.1.0 - Production
CORE 10.2.0.1.0 Production
TNS for 32-bit Windows: Version 10.2.0.1.0 - Production
NLSRTL Version 10.2.0.1.0 - Production


Difference between INTEGER and INT



What is the difference between Integer and int?


Integer is a class(Wrapper Class) defined in the "java.lang" package,where as int is a primitive data type.

Integer can be used as an argument for a method that requires an object,where as int can be used for calculations.

An int holds a number, whereas Integer is a pointer that can reference an object that contains a number.

Integer can handle null. For int null would become 0(zero) and int cannot express null.

Here's list of Wrapper Classes and Primitive Data Types available in Java.

Wrapper Class
Primitive data type
Integer
Int
Byte
byte
Character
char
Short
short
Double
double
Boolean
boolean
Long
long

Difference between Abstract class and Interface ?


Difference between Abstract class and Interface ?

Here's a very important concept in Java - to undertand the differences between abstract class and Interface.
its bit tricky,but understanding the usage and implementation gives a clear picture 

Below listed few major difference between these two...

             Abstract Class                                                                     Interface  
If the functionalites(declaration and definition) is same for all classes  then we use Abstract class.

If the declaration is same but the implementation logic is going  differ from  class to class then we use Interface
abstract class can contain abstract and non-abstract methods

every method in interface should be abstract
in abstract class there can be default and instance variables also

by default what ever variables we declare in interface are public static final
An Abstract Class can contain default Implementation
Interface should not contain any implementation. An Interface should contain only definitions but no implementation
When a class inherits from an abstract, the derived class must implement all the abstract methods declared in the base class
Interface is included in Java to support multiple inheritance.
1) It should contain abstract methods only.
2) It contains only final fields.
3) Subclass may implements any no of interfaces.

Abstract class can provide complete, default code and/or just the details that have to be overridden.

An interface cannot provide any code, just the signature.
Abstract classes are fast.
Interfaces are slow as it requires extra indirection to find corresponding method in the actual class

any class can extend an abstract class..


Only an interface can extend another interface


Difference between Statement and Prepared Statement


Difference Between Statement and Prepared Statement ?

Prepared Statement is Pre-compiled class, but Statement is not.
So in PreparedStatement the execution will be faster.

Statement:
when you submit a simple statement to the database, at first the DataBase Managment System  parses it and sends it back with the result, when you send the same statement again the DBMS server parses it and sends back the result, so here a lot of time is consumed/wasted because the statement is parsed again and again though it has been sent twice or thrice.

it consumes a lot of time and response time will be slow.

Prepared Statement
When you  want to execute a statement object number of times when you submit a PreparedStatement the DBMS server parses it and creates a execution plan. This e-plan can be used when you again send the same statement to the database.That is the DBMS server executes the compiled statement rather that executing it from first, hence we get an precompiled statement.

And also the advanatge of using this PreparedStatement is it is used to send dynamic sql statements, which you can pass values later rather than giving the values at the time of creation.

Monday, 4 June 2012

Foo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details


Problem:
Note: Foo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for detail
.
Solution  
This comes up in Java 5 and later if you're using collections without type specifiers (e.g., Arraylist() instead of ArrayList<String>()).
It means that the compiler can't check that you're using the collection in a type-safe way, using generics.
To get rid of the warning, just be specific about what type of objects you're storing in the collection. So, instead of using
List myList = new ArrayList();
use
List<String>myList = new ArrayList<String>();


Difference Between Collections.sort() and Arrays.sort() ?


Difference Between Collections.sort() and Arrays.sort() ?

Let us look at the basic differences between Collections.sort() and Arrays.sort().
Both the methods are used to sort a group of elements, but which method to use should be decided as per the requirement.
Below are couple of difference between these two methods which gives a clear understanding of  "when /how to implement"

Collections.sort()

Arrays.sort()
Collections.sort operates on a List
Arrays.sort operates on an array

Use Collections.sort() if you're dealing with something that implements the Collection interface - example: ArrayList

Use Arrays.sort() if you're dealing with an Array
Collections.sort() has a input as List so it does a translation of List to array and vice versa which is an additional step while sorting.
So this should be used when you are trying to sort a list.

Arrays.sort is for arrays so the sorting is done directly on the array.
So clearly it should be used when you have a array available with you and you want to sort it.


Difference Between HashMap and HashTable ?

Difference Between HashMap and HashTable ?

HASH MAP
HASH Table

Both provide key-value access to data
Both provide key-value access to data

HashMap not synchronized
Hashtable is synchronized

iterator in the HashMap is fail-safe

Fail-safe is relevant from the context of iterators.If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally",a concurrent modification exception will be thrown

Synchronized means:- only one thread can modify a hash table at one point of time.
Basically, it means that any thread before performing an update on a hash table will have to acquire a lock on the object while others will wait for lock to be released.
you can make Hashmap as synchronize :
Map m = Collections.synchronizeMap(hashMap)


Since HashMap is not thread safe so it is faster than hashTable



HashMap:  if you are sure that this hashmap will not be accessed by multiple threads 

but if you want to multiple thread to access then use HashTable.