In previous blog I covered different interface of java.sql package that are important for writing jdbc code to get connected to the database. In this blog we will study a sample code on how we can get connected to the Oracle data base and execute a sample query to get the Result set and print it on the console.
For this purpose we are assuming that oracle is installed on our local system and we have a schema called "vinodoracle" and a password "vinodoracle". We also assume we do have a table with name EMP with column names "EMPLOYEEID","NAME" and "SALARY" of types NUMBER,VARCHAR2 and NUMBER respectively.
The table does look as below :
The comments in the below program are self explanatory.
The Line #22 loads the OracleDriver class and initializes the driver. The line #24 supplies the url,uid and pwd and creates a coonection to oracle data base. We assume Oracle is installed on local machine so localhost in our url. Line #27 obtains a statement type object from the connection and Line #29 executes SELECT query and stores the result in ResultSet type object of Oracle. Which can then be printed as we are doing.
We are catching ClassNotFoundException for Class.forName("") call. If we don't have oracle supplied Driver jar in our class path we do catch this exception. So make sure we have ojdbc14jar in our class path .
Please focus on how we are retrieving the values from the record set. RecordSet interface provides methods like getInt, getString etc.. to retrieve the values from the current record set. We can either pass Column Name or Column Number as parameter. In the below code at Line #35 we use Column Name to get the values of EMPLOYEEID and NAME . But we are getting SALARY by using column number as parameter to getNumber . Also note that column numbers are not zero based . They start from one.