?
Solved

java.lang.nullpointerexception

Posted on 2004-08-11
11
Medium Priority
?
488 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 

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 500 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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month14 days, 20 hours left to enroll

771 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