Solved

java.lang.nullpointerexception

Posted on 2004-08-11
11
469 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
Comment Utility
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
Comment Utility
>> 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
Comment Utility
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
 

Author Comment

by:kassidy2010
Comment Utility
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
Comment Utility
>> 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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Author Comment

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

Author Comment

by:kassidy2010
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
sumHeights  challenge 17 59
triangle challenge 4 75
What is the latest versions eclipse neon 2 113
Java Timer (static) 9 0
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
This video teaches viewers about errors in exception handling.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

763 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now