Showing posts with label oracle. Show all posts
Showing posts with label oracle. Show all posts

Saturday, 6 October 2012

Executing Query from Java

Executing Query from Java



Before this you need to connect to database, refer to this post
Connection conn = null;
try{
         DbConnectionProvider dbConnectionProvider = new DbConnectionProvider();
         conn = dbConnectionProvider.connect();
         Statement stmt=conn.createStatement();
         String query = "SELECT NAME, AGE FROM DETAILS_TABLE";
                ResultSet rs = stmt.executeQuery(query);
                while (rs.next()){
                      System.out.println(rs.getString(1));
}}

how to connect java to oracle database

Connect Java to Oracle Database


package com.action.dbConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnectionProvider {
      String serverName = "119.45.2.23";
      String sid = "xyz";     // String sid given by Oracle
      String username = "uid";
      String password = "pwd";
      String driverName = "oracle.jdbc.driver.OracleDriver";
      String portNumber = "2008";
      Connection connection = null;
     
      public Connection connect() {
            try {
System.out.println("Inside class DbConnectionProvider, Method connect()");
                  // Load the JDBC driver
                   Class.forName(driverName);
                  // Create a connection to the database
String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
connection = DriverManager.getConnection(url, username, password);
            } catch (ClassNotFoundException e) {
                // Could not find the database driver
                  System.out.println("Could not find the database driver");
                  e.printStackTrace();
            } catch (SQLException e) {
                // Could not connect to the database
                  System.out.println("Could not connect to the database");
            } finally {
                 
            }
            return connection;
      }