Monday, March 3, 2014

JDBC Coding Steps

 

Following are different steps involved in a Java Program using JDBC to perform Database operations:
 
  • Load the Driver Class
  • Create a Connection to the Data Base providing the necessary privileges and arguments.
  • Get the Statement type Object from the Connection
  • Execute the Data Base Query on the Statement type object obtained.
  • Get the Result Set from the query executed. Process the records
Now we shall see each step with JDBC coding point of view to connect with Oracle data base.
Please note the interfaces from Java [ provided in java.sql and javax.sql remain the same independent of the Data Base server we use. However the parameters we pass to load the vendor specific implementation will change].
 

Loading the Driver Class:


JDBC suggests us to  use reflection to load the driver class of specific DB vendor. Internally the Driver class would implement some static block executing initializing the Driver when we do load the class. The general syntax is as follows:

Class.forName("<<driverpackage.Driverclass>>");

For loading Oracle database we need to do:

Class.forName("oracle.jdbc.driver.OracleDriver");

where oracle.jdbc.driver.OracleDriver is the DriverClass provided by Oracle following JDBC specifications.

Please make sure the jar that has OracleDriver class which comes with oracle installation should be in our class path.

Creating Connection :


After loading the DriverClass we need to establish connection to the database server. To do this we get a Connection type object of DriverManager. The general syntax is:

Connection con=DriverManager.getConnection(url,uid,pwd);

Where url specifies the url specified by Database vendor to connect to the DataBase Server. uid is the userId and pwd is the password .

Example:
 To get Connection to  Oracle DataBase server running on the localHost:1521 an instance XE and schema (user) admin and password 123 we get Connection as follows:

Connection con=DriverManager.getConnection("jdbc:oracle:thin@localhost:1521:XE","admin","123");


Get Statement type Object:


We need a Statement type object from the Connection type to interface and communicate with the database. Following is the syntax how we get a Statement type from the Connection.

Statement st= con.createStatement();


Execute the Query :


Once we have the Statement we can use execute(),executeQuery() etc.. to send queries to the DataBase.

Example:
ResultSet rs=st.executeQuery("SELECT * FROM EMPLOYEE");

Now with the the user can develop business specific code to handle the data got from the database in the above case ResultSet rs can be used to manipulate and write business specific .

The thing to note here is Connection,Statement and Result set are the interfaces defined by JDBC standard which all the DB vendors need to implement in order for java to support them.



 
 

No comments:

Post a Comment