0

In a simple servlet code,
I get a NULLPointerException thrown while giving query to prepared statement.

By what i understand, null pointer exception is thrown when an object defined null is given some new value.

But am not sure how to change the following code to run properly.

import java.sql.*;

public class DataLogic {
    static Connection con;
    static PreparedStatement ps;
    static ResultSet rs;

    DataLogic() {
            try{
                Class.forName("com.mysql.jdbc.Driver");
                con=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","");
            } catch(Exception e){
                e.printStackTrace();
            }
    }

    public static boolean login(String user, String pass)   {
        boolean b=false;
        try{
        /*Exception thrown in next line*/
            ps=con.prepareStatement("select * from login where uname=? and pass like ?");
            ps.setString(1, user);
            ps.setString(2, pass);
            rs=ps.executeQuery();
            //System.out.print(b=rs.next());
        } catch(Exception e){
            e.printStackTrace();
        }
        return b;
    }

}

PS: This is invoked from a servlet.

Update:

java.lang.NullPointerException at data.DataLogic.login(DataLogic.java:22) at serv.login.doPost(login.java:35) at serv.login.doGet(login.java:26) at javax.servlet.http.HttpServlet.service(HttpServlet.java:621) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Blockquote

Pls help. Thnks in advance.

harvish
  • 195
  • 1
  • 4
  • 11
  • 2
    Please post the exception stacktrace. – sleske Jul 31 '13 at 13:38
  • @sleske: stack traces are generally unhelpful in NPEs. It'd be more helpful if OP itself told which variable at which line exactly is `null` (as the OP already did in code comment). The `con` variable is just `null` likely because of the completely broken exception handling in the constructor. Harvish, you've other severe problems in this code: http://stackoverflow.com/questions/9428573/is-it-safe-to-use-a-static-java-sql-connection-instance-in-a-multithreaded-syste/ – BalusC Jul 31 '13 at 13:40
  • 3
    Wild non-educated guess: you're invoking `DataLogic.login(...)` without having instantiated a `DataLogic` object before, so there is no `con` object. – mthmulders Jul 31 '13 at 13:41
  • okay.. first I put that in a static block. I got exception even that time .. static blocks shud execute when the class is called right? – harvish Jul 31 '13 at 13:44

4 Answers4

3

It sounds like either Class.forName or DriverManager.getConnection failed, so con was never assigned a non-null value.

Rather than just printing the stack trace there, it would be better to throw an exception - possibly a runtime exception if you want (as you can't really "handle" this situation). Then you can find the error as quickly as possible, instead of pretending that the constructor has succeeded properly. Swallowing exceptions like this almost always just delays a problem rather than fixing it, and it makes it much harder to diagnose later.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Great Jon Skeet ! Thanks ! mysqlconnector in my system has moved. and that is why Class.forName() failed Sorry for the Basic mistake. – harvish Jul 31 '13 at 14:03
0

Null Pointer means in the line;

ps=con.prepareStatement("select * from login where uname=? and pass like ?");

Something is null, of this line only con can be null. Therefore, I presume your calling the static method before an instance of the object has been constructed too initialise con.

Robadob
  • 5,319
  • 2
  • 23
  • 32
0

The code you are posting cannot work. You are initializing the con variable in the constructor of the object.

The method accessing the object however is in a static method which does require a constructor of any object to be called before.

Please do not mix up static and non static methods in that way. If you require the login method to be static, then initialize the connection in a static initializer. However, I do not see a reason for using a static method in that context.

Matthias
  • 3,582
  • 2
  • 30
  • 41
0

You declared the "login" method as static! Which means it instance less, or in other words the constructor is never called bevor. Haven't you run this through your debugger?

You could do something like

public static boolean login(String user, String pass)   {
        DataLogic logic = new DataLogic();
        boolean b=false;
        try{
        /*Exception thrown in next line*/
            ps=logic.con.prepareStatement("select * from login where uname=? and pass like ?");
            ps.setString(1, user);
            ps.setString(2, pass);
            rs=ps.executeQuery();
            //System.out.print(b=rs.next());
        } catch(Exception e){
            e.printStackTrace();
        }
        return b;
    }

For this your variable "con" needs to be public, or you have to provide a getter method.

Rene M.
  • 2,660
  • 15
  • 24