Solved

java.lang.nullpointerexception

Posted on 2004-08-11
11
470 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
 

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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
topping1 challenge 7 73
Core Java. What output will be and why ? 6 66
Java asynchronous logging 4 50
DO we need Java installed on a Windows PC and WHY ? 13 97
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
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 about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

910 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

19 Experts available now in Live!

Get 1:1 Help Now