April 12, 2011

JDBC Code Example

1) Download and install Oracle 10g Express edition from the following link (note down the admin password chosen during installation).
Verify that the installation was successful - in the Start > Programs > 'Oracle Database 10g Express Edition' should show up.

2) Start the Oracle 10g Services by following the steps,
- Go to Start > Run
- Type services.msc and click OK
- In the Services window find the 5 Oracle services and start all of them, starting with the OracleServiceXE service

3) Change Oracle's Web Manager Application port number:
- Open the SQL*Plus Command Prompt window
- Type the command: connect
- Log in as user 'system' and type the password chosen during installation
- Execute the following command at the SQL prompt, (where 8090 is the new port number),


4) Add the ojdbc14.jar file from the following path of the installed Database folder:
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib into the build path of the Java Application

5) The Oracle JDBC driver class is oracle.jdbc.OracleDriver and the JDBC connection string to be used in the DriverManager.getConnection() method is jdbc:oracle:thin:@localhost:1521:xe

Note: This information is procured from vendor documentation, in this case, Oracle 10g documentation.

6) At the SQL command prompt, paste the following SQL statement to create a new table,

create table jdbcdemo ( 
    firstname varchar2(25),
    lastname varchar2(25),
    age number(2),
    dob date

Next, at the SQL prompt, execute the following command, 


7) Create a java class, JDBCdemo.java and add the following code,

package info.icontraining.jdbc;

import java.sql.*;

public class JDBCdemo {

   public static void main(String[] args) throws SQLException, ClassNotFoundException {

      Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "system");
      Statement stmt = conn.createStatement();
      stmt.executeUpdate("insert into jdbcdemo values ('Dinesh', 'PC', 32, '1-JAN-1978')");
      stmt.executeUpdate("insert into jdbcdemo values ('Tanvi', 'DC', 27, '1-JAN-1984')");
      stmt.executeUpdate("insert into jdbcdemo values ('Laksh', 'DC', 2, '1-MAY-2009')");
      ResultSet rs = stmt.executeQuery("select * from jdbcdemo");
      while (rs.next()) {  
         System.out.println("Name: " + rs.getString(1) + " " + rs.getString(2));
         System.out.println("Age: " + rs.getInt("age"));
         System.out.println("DOB: " + rs.getDate(4).toString());

8) Run the code as a standalone Java application

No comments:

Post a Comment