Tuesday, June 24, 2014

example java and JDBC code 1

(1) First need .jar file for JDBC Thin client-side driver.
(2) http://www.oracle.com/technetwork/indexes/downloads/index.html -->
     click on  Drivers --> JDBC Drivers
(3) Click on "Oracle Database 11g Release 2 (11.2.0.4),(11.2.0.3),(11.2.0.2.0),(11.2.0.1.0) drivers"
(4) we currently using 11.2.0.2.0
(5) So i clicked under 11.2.0.2.0 --> ojdbc6_g.jar
(6) the file got downloaded
(6) And then inside NetBeans IDE 8.0 for my project,
     right-click on Libraries folder --> Add JAR/Folder --> go to ojdbc6_g.jar file location
(7) Here is my example java code:


package dbtest;

import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import oracle.jdbc.*;


public class Dbtest
{
 
    public static void main(String[] args)
    {
       
        Connection connection = null;
       
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        }
        catch (ClassNotFoundException e)
        {
            System.out.println("Stack Trace 1");
            e.printStackTrace();
        }
       
        System.out.println("Passed 1: Found oracle.jdbc.driver.OracleDriver");

        try
        {
            connection=DriverManager.getConnection("jdbc:oracle:thin:@myhost:mySID",
                                                                             "username", "password");
        }
        catch (SQLException e)
        {
            System.out.println("Stack Trace 2");
            e.printStackTrace();
        }
       
        System.out.println("Passed 2: Successful connection to db");

        if (connection != null)
        {
            try
            {
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT FIRST_NAME,LAST_NAME from dbo.person where dbo.person.person_id = '5138'");
                while (rs.next())
                {
                    String fn = rs.getString("FIRST_NAME");
                    String ln = rs.getString("LAST_NAME");
                    System.out.println(fn);
                    System.out.println(ln);
                }
            }
            catch (SQLException e)
            {
                e.printStackTrace();
            }
        }
        else
        {
            System.out.println("connection is NULL! You did not connect to db!");
        }  
    }
}

No comments:

Post a Comment