Solved

java.lang.nullpointerexception

Posted on 2004-08-11
11
474 Views
Last Modified: 2012-06-21
Hello everyone,
  Quick easy question!  I am getting a nullpointerexception when using getConnection() method.  I am trying to connect to an already established db connection.  I am not sure what I am doing wrong.

here is alittle idea of what I'm doing:

Connection con = null;
Datasource datas = null;

con = datas.getConnection();

I have also tried this:

Connection con = null;
Datasource datas = null;


try{

  con = getconnection();
}catch (Exception e) {e.printStackTrace(); throw e;}
.
.
.
.
private Connection getconnection() throws SQLException{ return ds.getConnection();}

Hope this is good enough.  Thanks for all your help!
0
Comment
Question by:kassidy2010
  • 5
  • 3
  • 2
  • +1
11 Comments
 
LVL 37

Expert Comment

by:zzynx
ID: 11778173
Connection con = null;
Datasource datas = null;   // Here datas is NULL

con = datas.getConnection();  // Here datas is still NULL  ;°) You try to call the function getConnection() on a Null Pointer => NullPointer Exception
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11778206
>> private Connection getconnection() throws SQLException{ return ds.getConnection();}
And what is ds? Where does it get its non-null value?
0
 
LVL 92

Expert Comment

by:objects
ID: 11779087
you need to know the name of the datasource you are using:

Context initCtx = new InitialContext();
Connection con = null;
DataSource datas = datac = initCtx.lookup("dsname");
con = datas.getConnection();
0
MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

 

Author Comment

by:kassidy2010
ID: 11779193
first from zzynx:
  I forgot I have also tried with not intializing datas:
declearing as follows
Datasource datas;

That still didnt work, but I am not sure how to initalize it or what to initialize it too.

the second from zzynx:
  I made a mistake, ds is suppose to be datas.

As for objects.  I will try that to see what happens.  That seems to be right.  I dont want to make another database connection I want to use one that is already established.  Thanks for your help!!!
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11779229
>> I have also tried with not intializing datas
>> Datasource datas;

That's the same as writing

        Datasource datas = null;

Every non-initialized Object is by default null.
0
 

Author Comment

by:kassidy2010
ID: 11779257
Thats waht I figured, how would I go about getting the connection?  should objects solution work?
0
 

Author Comment

by:kassidy2010
ID: 11779279
for objects:
  What is datac?  and is the datasource name the name of the database or the name of the data connect?
0
 
LVL 92

Expert Comment

by:objects
ID: 11779349
typo, should be:

DataSource datas = initCtx.lookup("dsname");

the name is the name of the data source in your configuration.

0
 
LVL 3

Accepted Solution

by:
vikraman_b earned 125 total points
ID: 11779952
Hi,
Try this method to get the connection...

public static Connection getConnection()
    {
        Connection connection = null;
        boolean debug = true;

        if ( debug )
        {
            try
            {
                  //System.out.println("Loading Oracle Driver......");
                Class.forName("oracle.jdbc.driver.OracleDriver");
            } catch (ClassNotFoundException e) {
                        //System.out.println("Failed to Load Oracle Driver......"+e.toString());
                return null;
            }

            try {
                        //System.out.println("Getting Connection......");
                connection = DriverManager.getConnection(
                "jdbc:oracle:thin:@xxx.xxx.xx.xxx:1526:xyz",
                "username", "password");
            } catch (SQLException e) {
                        //System.out.println("Failed to Get Connection......"+e.toString());
                return null;
            }
           
            return connection;
        }

        try
        {
            // obtain connection from container's datasource
            if ( initCtx==null )
            {
                initCtx = new InitialContext();
            }
           
            DataSource ds = (DataSource)
                initCtx.lookup("");
               
            if ( ds==null )
            {
                logger.warn("Null Datasource [datasource="
                    +""+"]");
                //System.out.println("Null Datasource [datasource="
                        //+""+"]");
                           
                return null;
            }

            logger.info("Getting connection from [datasource="
                +""+"]");
            //System.out.println("Getting connection from [datasource="
                  //+""+"]");
                      
            connection = ds.getConnection();
           
        } catch (Exception e) {
           logger.error("Error while obtaining connection : "+e);
           //System.out.println("Error while obtaining connection : "+e.toString());
            return null;
        }

        return connection;
    }
0
 

Author Comment

by:kassidy2010
ID: 11783054
Ok so I tried objects solution and I got another error message :(

objects wrote:

Context initCtx = new InitialContext();
Connection con = null;
DataSource datas = datac = initCtx.lookup("dsname");
con = datas.getConnection();

I did the following and got this error:
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial

I checked my global properties file and its good and I also checked my class path which looks good.  

The second question I have is:  Is objects solution esablishing a new db connection?  I already have db connections open can I just use them or is that what objects solution is doing.....thanks for everyones help!!!
0
 

Author Comment

by:kassidy2010
ID: 11784141
I accepted vikraman_b's answer because I used his method as a guidline to understanding how the db connection works.  


THANKS TO ALL FOR YOUR HELP!!!!!!!!!!!!!
0

Featured Post

Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to get all the API from website? 11 92
Android studio getdrawable(int) is deprecated 4 88
servlet example 17 33
Glassfish admin console not working 1 16
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This video teaches viewers about errors in exception handling.

825 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question