Looking for a JavaEE Architect or Potential Tech Co-Founder?
Please don't hesitate to contact me.

Connect to oracle database in java language

This code connects to an oracle database using java programming language.

This to remember:
1.) You must add ojdbc14.jar to the project's build path.
2.) Oracle's driver name: oracle.jdbc.driver.OracleDriver
3.) Connection string: jdbc:oracle:client:@server:port:database
Example: jdbc:oracle:thin:@localhost:1521:xe
4.) It is assumed that we have a table employee(firstname(string), lastname(string)) in the database.

package com.kbs.demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Runner {
 public static void main(String args[]) throws Exception {
  Class.forName ("oracle.jdbc.driver.OracleDriver");

  Connection conn = DriverManager.getConnection
  ("jdbc:oracle:thin:@localhost:1521:xe", "demo", "demo");
  // @machineName:port:SID,   userid,  password
  try {
   Statement stmt = conn.createStatement();
   try {
    ResultSet rset = stmt.executeQuery("select firstname from employee");
    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 { conn.close(); } catch (Exception ignore) {}

Connect to oracle database in java language Connect to oracle database in java language Reviewed by Edward Legaspi on Monday, September 05, 2011 Rating: 5

No comments:

Powered by Blogger.