Link to home
Start Free TrialLog in
Avatar of Amit
AmitFlag for United States of America

asked on

Null pointer exception when setting up a global oracle data source

Hi,

In the following code i am trying to create a global oracle connection. But I am getting a null pointer exception when setting the oracle url. Any ideas why, also what is the best practise of creating a global database connection which can be used in all parts of the code
public class CheckFirst {
  
 
 
// Set up Oracle Data Structures
 
public static OracleDataSource ods;
public static Connection conn; 
public static ResultSet rset;
public static Statement stmt;
 
//Set up Teradata Data Structures
 
 
 
public static void openOrclConn()
{
	try
    {	
	ods.setURL("jdbc:oracle:thin:@//alpha.beta.abc.com:1521/alpha");
	ods.setUser("abc123");
	ods.setPassword("abc123");		
	ods.getConnection();
	conn.setAutoCommit (false);
	stmt = conn.createStatement ();
    } catch (Exception e) {
        e.printStackTrace();
   }
}
 
public static void closeOrclConn()
{
	try
    {
	rset.close();
	stmt.close();
	conn.close();
    } catch (Exception e) {
        e.printStackTrace();
   }
}
 
 
public static void main (String args []) 
 
{
	
	openOrclConn();
	
}
 
}

Open in new window

Avatar of sirtam
sirtam
Flag of Norway image

Hi.

Could you please post the error message?
Avatar of Amit

ASKER

java.lang.NullPointerException
      at CheckFirst.openOrclConn(CheckFirst.java:58)
      at CheckFirst.main(CheckFirst.java:87)

The line numbers can be off a little bit because I removed two three lines when I posted the code

Its happening in this line

      ods.setURL("jdbc:oracle:thin:@//bia.vip.ebay.com:1521/bia");


Avatar of Amit

ASKER

ok this is what i did and it seems to have fixed it

I added the line

ods = new OracleDataSource();  in the function

public static void openOrclConn()
Yes, you cannot open an object before making it.

When you are using object like this the variable will be there, but empty, therefore you will get an null pointer.

And a tip:
If possible I would try to declare the variables  ods, conn, rset and stmt as not static.
If you use static variables you say its only one (ever) object of it, and that can make problems later.
ASKER CERTIFIED SOLUTION
Avatar of sirtam
sirtam
Flag of Norway 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
Avatar of Amit

ASKER

Thanks alot for this