Link to home
Start Free TrialLog in
Avatar of gazdzid
gazdzidFlag for United States of America

asked on

DB Connection code - Learning ajax

I would like assistance testing the following database connection Please assume that all hidden values are correct.  I am not sure how to test it as I cannot view my console (working on that)Found below is the java for the connection and the java that invokes the method (I hope my syntex is correct). both java files are provided DBConnection.java and then OrgDrillServlet.Java
public class DBConnection {
	private static DBConnection obj;
	private static Connection con;
	private static Statement stmt;
	
	private DBConnection(){
		
	}
	 public static DBConnection getInstance(){
	 	if(obj==null){
	 		return new DBConnection();
	 	}else{
	 		return obj;
	 	}
	 }

	

	/**
	 * @return Returns the conn.
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws SQLException
	 */
	public static Connection getConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
		Connection con = DriverManager.getConnection("jdbc:oracle:thin:@1111.1111.1111.1111:1111:wwwwww","www_wwwwwww","xxxxxxx");
		return con;
	}
	public Statement getStatement() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
		 con = getConnection();
		 stmt = con.createStatement();
		return stmt;
	}
	public void closeConnection() {
		try {
			stmt.close();
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	

}



package com.testajax;



import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;


/**
 * Servlet implementation class OrgDrillServlet
 */
public class OrgDrillServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OrgDrillServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String key = request.getParameter("DD_ORG_CO_KEY");
		String businessKey = request.getParameter("DD_ORG_BUS_KEY");
		
		System.out.println("DD_ORG_CO_KEY ID IS :::"+key);
		System.out.println("DD_ORG_BUS_KEY ID IS :::"+businessKey);
		
		
		Statement stmt= null;
		DBConnection DBConn =null;
		try{
			DBConn  = DBConnection.getInstance();
			stmt = DBConn.getStatement();
		}catch (SQLException exception){
			System.out.println("SQL Exception while connecting to DB!");    	
		} catch (InstantiationException exception) {
			System.out.println("Cannot create a DB connection!");    			
		} catch (IllegalAccessException exception) {
			System.out.println("Acess Denied to connect!");    			
		} catch (ClassNotFoundException exception) {
			System.out.println("Class not found!");    			
		}
		
		
		response.setContentType("text/xml");
		response.setHeader("Cache-Control", "no-cache");
		
		// If the key is null we will assume that this is a call to populate sub business names
	    if (key != null) 
	    {
	    	System.out.println("Populating the business names...");	
			String resp = "";
			resp = "<?xml version='1.0'?>";
			try {

				PrintWriter out = response.getWriter();
				// in the query part you may have to add a where clause using the keys that you have recieved from client
				 	resp = resp + "<Business>"; 
					String lsQuery = " (SELECT ORG_KEY , ORG_NAME  FROM ORG_TAB ORDER BY ORG_NAME ASC)";
					ResultSet rs=stmt.executeQuery(lsQuery);
				
					String BusinessId = "";
					String BusinessName ="";
			
					while (rs.next()) {
						BusinessId 		= rs.getString("ORG_KEY");
						BusinessName 	= rs.getString("ORG_NAME");
						resp = resp + "<BusinessName id='"+BusinessId+"'>"+BusinessName+"</BusinessName>";
	            	}
	            	resp = resp + "</Business>";	
	            
				System.out.println("The XML data retrieved is:");
				System.out.println(resp);
				
				out.write(resp);
				out.flush();
			} catch (Exception exception) {
				System.out.println("Error occured when fecthing the business names:"
						+ exception);
			}
	    }
	    // request for displaying sub business names
	    else
	    {
	    	
	    	System.out.println("Populating the sub business names...");	
			String resp = "";
			resp = "<?xml version='1.0'?>";
			
			try {

				PrintWriter out = response.getWriter();
								// in the query part you may have to add a where clause using the keys that you have recieved from client	
				resp = resp + "<Business>"; 
					String lsQuery = " (SELECT ORG_KEY , ORG_NAME  FROM ORG_TAB ORDER BY ORG_NAME ASC)";
					ResultSet rs=stmt.executeQuery(lsQuery);
				
					String BusinessId = "";
					String BusinessName ="";
			
					while (rs.next()) {
						BusinessId 		= rs.getString("ORG_KEY");
						BusinessName 	= rs.getString("ORG_NAME");
						resp = resp + "<BusinessName id='"+BusinessId+"'>"+BusinessName+"</BusinessName>";
	            	}
	            	resp = resp + "</Business>";	
	            
				System.out.println("The XML data retrieved is:");
				System.out.println(resp);
				
				out.write(resp);
				out.flush();
			} catch (Exception exception) {
				System.out.println("Error occured when fecthing the sub business names:"
						+ exception);
			}
			
	    }
	}	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

Open in new window

Avatar of akilaru
akilaru
Flag of United States of America image

You should download the oracle jdbc driver and then use "oracle.jdbc.OracleDriver" (thin driver to test your connection)
Avatar of gazdzid

ASKER

I do have jdbc driver but not sure how to test the provided code.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
                Connection con = DriverManager.getConnection("jdbc:oracle:thin:@1111.1111.1111.1111:1111:wwwwww","www_wwwwwww","xxxxxxx");
             

this is wrong,
you are loading a JDBCODBC driver and then trying to connect to Oracle DB...

it should be

Class.forName("oracle.jdbc.driver.OracleDriver");
DriverManager.getConnection("jdbc:oracle:thin:@1111.1111.1111.1111:1111:wwwwww","www_wwwwwww","xxxxxxx");


I am assuming that you will fix the IP and password etc with actual values before attempting to connect.
Also please note that Oracle jdbc drivers are not preloaded on systems. You will have to download them as Akilaru is suggesting.
ASKER CERTIFIED SOLUTION
Avatar of kadaba
kadaba
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
once you test this and it successfully connects to the Database, you can adapt the same in your class.

If you do not have the driver download the driver and test the same

Avatar of gazdzid

ASKER

I ran code found below on netbeans and received the following: will test and analyze code tomorrow. not sure exactly what happened will find out after analyzing. hopefully I am well on my way

run:
entering getDBConnection
Connection establised!
exiting getDBConnection
Could not connect!
BUILD SUCCESSFUL (total time: 1 second)

I used the code below next I will try kadaba's suggestion
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package helloworldap;
import java.sql.Connection;
import java.sql.DriverManager;

/**
*
* @author gazdzid
*/
public class HelloWorldAp {



/**
* This method will establish a connection to the DB
*
* @return <tt>Connection</tt> object which will hold an active connection
*/
public static Connection getDBConnection()
{
System.out.println("entering getDBConnection");

String driver = "jdbc:oracle:thin";// The driver used to connect to the
// oracle DB
String hostName = "xxx.xxx.xxx.xxx";// The host IP on which the oracle DB
// is set up
String port = "xxxx"; // The port number on which the Oracle Service
String dbName = "ORCL";// The service Name
String userName = "xxxx";// The user name
String password = "xxxx";// The password

Connection conn = null;
String url = driver + ":@" + hostName + ":" + port + ":" + dbName;

// String url = "jdbc:oracle:thin:@localhost:1521:ORCL";
// String userName = "xxxx";
// String password = "xxxx";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
DriverManager.getConnection("jdbc:oracle:thin:@xxxx.xx:xxx:xxx","xxx","xxx");


// Class.forName("oracle.jdbc.driver.OracleDriver");
// Register the class
// conn = DriverManager.getConnection(url, userName, password);
// The driver manager will get the connection to the data base

System.out.println("Connection establised!");

} catch (Exception exception)
{

System.out.println("Could not connect!");
System.out.println("Error:"+exception);

conn = null;
} finally
{

}

System.out.println("exiting getDBConnection");

return conn;
}

/**
* This is a test method to test the connection to the DB
*
* @return nothing
*/
public static void main(String args[])
{
Connection conn =HelloWorldAp.getDBConnection();

if (null == conn)
{
System.out.println("Could not connect!");
} else
{
System.out.println("Connection establised!");
}
}
}

in your above code.

 DriverManager.getConnection("jdbc:oracle:thin:@xxxx.xx:xxx:xxx","xxx","xxx");

shd be

 DriverManager.getConnection(url,"xxx","xxx");//xxx are user id and pwd.
Avatar of gazdzid

ASKER

Found below is the results after running the code found below (I chose to hard code the values for the url,name.password)
run:
entering getDBConnection
Connection *a* establised!
exiting getDBConnection
Could *b* not connect!
BUILD SUCCESSFUL (total time: 3 seconds)
I am hoping that you could explain my observation for step 6.) conn is returning as null and I am not sure if this is good or bad the console shows Could *b* not connect! (code found below)

This is how I understand the results found below:
1.) When I click run found on my ide run: is posted ted to the console.
2.) The main method is found and .getDBConnection(); is invoked
3.) entering getDBConnection shows that we have entered the method called getDBConnection();
4.) Connection *a* establised! Shows that a connection has been made. If the connect was not made the console would show Could *a* not connect! Error:java.sql.SQLException: Io exception: The Network Adapter could not establish the connection
5.) exiting getDBConnection show that we are leaving the method getDBConnection(); with a connection to the database and the value of the conn value is returned to the main value.
6.) Could *b* not connect! conn appears to be returning as null and I am not sure if this is good or bad the console shows Could *b* not connect!. Please note I did add *a* and *b* for purposes of anysis.


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package helloworldap;
 import java.sql.Connection;
import java.sql.DriverManager;

/**
 *
 * @author gazdzid
 */
public class HelloWorldAp {



    /**
     * This method will establish a connection to the DB
     *
     * @return <tt>Connection</tt> object which will hold an active connection
     */
    public static Connection getDBConnection()
    {
	System.out.println("entering getDBConnection");
	Connection conn = null;
	try
	{
            Class.forName("oracle.jdbc.driver.OracleDriver");
            DriverManager.getConnection("jdbc:oracle:thin:@xxx.xxx.xxx.xxx:xxxx:webdbdev","xxxx","xxxx");
	    System.out.println("Connection *a* establised!");
	} catch (Exception exception)
	{
	    System.out.println("Could *a* not connect!");
	    System.out.println("Error:"+exception);
	    conn = null;
	} finally
	{
	}
	System.out.println("exiting getDBConnection");
	return conn;
    }
    /**
     * This is a test method to test the connection to the DB
     *
     * @return nothing
     */
    public static void main(String args[])
    {
	Connection conn =HelloWorldAp.getDBConnection();
	if (null == conn)
	{
	    System.out.println("Could *b* not connect!");
	} else
	{
	    System.out.println("Connection *b* establised!");
	}
    }
}

Open in new window

Avatar of gazdzid

ASKER

Found below is the results after running the code found below (I chose to hard code the values for the url,name.password)
run:
entering getDBConnection
Connection *a* establised!
exiting getDBConnection
Could *b* not connect!
BUILD SUCCESSFUL (total time: 3 seconds)
I am hoping that you could explain my observation for step 6.) conn is returning as null and I am not sure if this is good or bad the console shows Could *b* not connect! (code found below)

This is how I understand the results found below:
1.) When I click run found on my ide run: is posted ted to the console.
2.) The main method is found and .getDBConnection(); is invoked
3.) entering getDBConnection shows that we have entered the method called getDBConnection();
4.) Connection *a* establised! Shows that a connection has been made. If the connect was not made the console would show Could *a* not connect! Error:java.sql.SQLException: Io exception: The Network Adapter could not establish the connection
5.) exiting getDBConnection show that we are leaving the method getDBConnection(); with a connection to the database and the value of the conn value is returned to the main value.
6.) Could *b* not connect! conn appears to be returning as null and I am not sure if this is good or bad the console shows Could *b* not connect!. Please note I did add *a* and *b* for purposes of anysis.


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package helloworldap;
 import java.sql.Connection;
import java.sql.DriverManager;

/**
 *
 * @author gazdzid
 */
public class HelloWorldAp {



    /**
     * This method will establish a connection to the DB
     *
     * @return <tt>Connection</tt> object which will hold an active connection
     */
    public static Connection getDBConnection()
    {
	System.out.println("entering getDBConnection");
	Connection conn = null;
	try
	{
            Class.forName("oracle.jdbc.driver.OracleDriver");
            DriverManager.getConnection("jdbc:oracle:thin:@xxx.xxx.xxx.xxx:xxxx:webdbdev","xxxx","xxxx");
	    System.out.println("Connection *a* establised!");
	} catch (Exception exception)
	{
	    System.out.println("Could *a* not connect!");
	    System.out.println("Error:"+exception);
	    conn = null;
	} finally
	{
	}
	System.out.println("exiting getDBConnection");
	return conn;
    }
    /**
     * This is a test method to test the connection to the DB
     *
     * @return nothing
     */
    public static void main(String args[])
    {
	Connection conn =HelloWorldAp.getDBConnection();
	if (null == conn)
	{
	    System.out.println("Could *b* not connect!");
	} else
	{
	    System.out.println("Connection *b* establised!");
	}
    }
}

Open in new window

Avatar of gazdzid

ASKER

I was able to achieve the following responce on my console. I added conn= to  the following line of code, which seemed to produce the desired result

conn = DriverManager.getConnection

entering getDBConnection
Connection *a* establised!
exiting getDBConnection
Connection *b* establised!
BUILD SUCCESSFUL (total time: 1 second)

Now that I believe that it is working properly should I paste this code to my connection file or should I paste all except the "main"
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package helloworldap;
 import java.sql.Connection;
import java.sql.DriverManager;

/**
 *
 * @author gazdzid
 */
public class HelloWorldAp {



    /**
     * This method will establish a connection to the DB
     *
     * @return <tt>Connection</tt> object which will hold an active connection
     */
    public static Connection getDBConnection()
    {
	System.out.println("entering getDBConnection");

	Connection conn = null;
	
	try
	{
            Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
        
 conn = DriverManager.getConnection("jdbc:oracle:thin:@xxx.xxx.xxx.xxx:xxxx:webdbdev","xxxx","xxxx");


	    System.out.println("Connection *a* establised!");
          //  System.out.println(c);

	} catch (Exception exception)
	{

	    System.out.println("Could *a* not connect!");
	    System.out.println("Error:"+exception);

	   conn = null;
	} finally
	{

	}

	System.out.println("exiting getDBConnection");

	return conn;
    }

    /**
     * This is a test method to test the connection to the DB
     *
     * @return nothing
     */
    public static void main(String args[])
    {
	Connection conn =HelloWorldAp.getDBConnection();

	if (null == conn)
	{
           
	    System.out.println("Could *b* not connect!");
	} else
	{
	    System.out.println("Connection *b* establised!");
	}
    }
}

Open in new window

Avatar of gazdzid

ASKER

Hello Kadaba:

I did change the class name from HelloWorld to your suggested name of DBUtil
Avatar of gazdzid

ASKER

Hello Kadaba:

can you verify that my code is correct at which point I can assign points and hopefully without to much pain can finish the previous question that you were kind enough to assist with.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gazdzid

ASKER

Hello kadaba:and Kuldeepchaturvedi:

Thank you for your assistance!!