简体   繁体   中英

Java - Null Pointer Exception passing records to a database

i'm lopping an arraylist filtering values and passing to a database, if the record is repeated, the code throws the exception then update the values in the database and jump to the next record. In the record 90 , 91 or 92 i'm getting this exception

java.lang.NullPointerException
at com.icc.utilidades.Conexion.actualizarEstadoAlumno(Conexion.java:4296)
at com.icc.controlador.AjaxControlador.doGet(AjaxControlador.java:227)
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.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
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:100)
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:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
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)

The code from conexion 4296 is a method and the exception is in the line of the preparedStatement

public int actualizarEstadoAlumno(String rut,String estado)
{
    try {
        ConexionBd();
        System.out.println("rut "+rut);
        System.out.println("estado "+estado);
        PreparedStatement enunciado = conexion.prepareStatement("update alumno set alu_estado = ? "
                  + "where alu_rut = ? ;");
        enunciado.setString(1, rut);
        enunciado.setString(2, estado);
        enunciado.execute();
        conexion.close();
        return 1;
    } catch (SQLException e) {
        return 0;
    }
}

When i print the values, they are not null , so why i'm getting this exception? , The database Connection i'm sure is ok, because when i use that code in other things this work's fine. Before the record number 90 the code pass the values to the database correctly. what could be the problem? help please.

this is the method where i connect to the database

public void ConexionBd()
{
    try 
    {
        Class.forName("org.postgresql.Driver");

        conexion = java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/final","postgres","*******");

        consulta = conexion.createStatement();  
    } catch (Exception e) {
        e.printStackTrace();
    }       
}

Null pointer exceptions occur when you are trying to refer to an object, say you're calling a method of that object, thinking the object exists but during the runtime the object doesn't exist at all.

For all the possibilities in the code where an object could be null depending on the runtime scenarios you have to put a null pointer check. I have tried to put some null pointer checks in your code, take a look below. I have also tried to correct your code a little, but it can be improved further as well. In the below code, I'm assuming conexion is a class level variable getting initialized outside of the given method.

One quick note, when it's about Null pointer exceptions, you cannot be sure of anything that goes at runtime :)

 public int actualizarEstadoAlumno(String rut,String estado)
{
    try {
        ConexionBd();
        System.out.println("rut "+rut);
        System.out.println("estado "+estado);
        if(conexion!=null){
           PreparedStatement enunciado = conexion.prepareStatement("update alumno set alu_estado = ? "
                  + "where alu_rut = ? ;");
           if(enunciado!=null){
                enunciado.setString(1, rut);
                enunciado.setString(2, estado);
                enunciado.execute();
                return 1;
           }
        }

    } catch (SQLException sqlEx) {
       //return 0;   This isn't a good way to handle exception. How will you know that SQL Exception has occurred? You need to handle the exceptions/weird things your code can run into.
       //log exception, use logger
       //print stack trace, handle the exception or throw it 
    } catch (Exception ex){
       //log exception, use logger
       //print stack trace, handle the exception or throw it 
    }finally{
         conexion.close(); // this is why finally was born.
    }
}

Your data field conexion seems to be null, so calling conexion.prepareStatement(..) throws the NPE. You should initialize the data field first before using it.

BTW. it is not a good style to simply catch the exception. You should at least log the error otherwise it is very difficult to find such errors.

I don't see anywhere you have initialized conexion. You have to use the new operator and initialize connexion within the scope of the try statement (connexion could have global scope, but I don't see it in the code snippet you have provided)

try this :

    try {
                ConexionBd();
                System.out.println("rut "+rut);
                System.out.println("estado "+estado);
           if(conexion!=null){
                PreparedStatement enunciado = conexion.prepareStatement("update alumno set alu_estado = ? "
                          + "where alu_rut = ? ;");
             }else{ 
  System.out.println("conexion not initialized (null)"); 

}
              enunciado.setString(1, rut);
                enunciado.setString(2, estado);
                enunciado.execute();
                conexion.close();
                return 1;
            } catch (SQLException e) {
                return 0;
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM