NullPointer when executing a PreparedStatement

1

I am trying to generate a ArrayList of users from a DB , the case is that when executing the PreparedStatement it returns a NullPointer and it tells me that the connection object is null, it is something that does not happen to me in other sentences that I have and they work.

I leave the code of Array and the code of class Conecta(Objeto Conect) :

      public class Usuario {

      private int id;
      private String nickName;
      private String password;    
      private String Email; 
      private ConectaDB conexion;

      public ArrayList<Usuario> getUsuarios(){
      Connection con = null;
      con = conexion.conecta();
      ArrayList<Usuario> Usuarios = new ArrayList();                    
      PreparedStatement getData = conexion.preparedStatement("SELECT IDUsuario, Nickname, Password, Email FROM usuario");           
      ResultSet data;

      try{            
      data = getData.executeQuery();
      while(data.next()){
        id = data.getInt(1);
        nickName = data.getString(2);
        password = data.getString(3);
        Email = data.getString(4);
      Usuario usser = new Usuario(data.getInt(1), data.getString(2), data.getString(3), data.getString(4));
      Usuarios.add(usser);
      }
       return Usuarios;
  } catch(SQLException e){              
    }  return Usuarios;
} 

And here is the code for the Conecta class:

  public class ConectaDB {

    public static Connection conecta(){

          Connection conecta=null;

          try{
              Class.forName("com.mysql.jdbc.Driver");
              String servidor="jdbc:mysql://xxxxxx:xxxx/bbdd_g1"; //conectamos a nuestra propia maquina
              String usuario="admin_g1";
              String password="a7586";
              //inicializamos objeto conecta, del tipo connection
              conecta = (Connection)DriverManager.getConnection(servidor, usuario, password);

          }catch(ClassNotFoundException e)
          {
              System.out.println(e.getMessage());
          }
            catch(Exception e) //capturar el resto de exceptions
          {
              System.out.println(e.getMessage());
          }finally{
              return conecta;//como el default de los case, pero se ejecuta si o si
          }

    }    

    public PreparedStatement preparedStatement(String x) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

Thanks for the help!

    
asked by Francrt 16.04.2018 в 09:13
source

2 answers

1

Even if we do not see the declaration of the object conexion , it seems that it gives you NullPointer because you are not accessing the object with the connection.

The connection is in con but the preparedStatement gets it out of connection, which is an instance of ConectaDB.

Edited: It should also be prepareStatement (without d in prepared)

Edited: You can use the following code. I have prepared the preparedStatement connection method to do the prepareStatement, but surely you should choose one of the following strategies.  - Make a static method that prepares the query by passing the connection.  - Make ConnectaDB an object that saves the connection and only passes the query to it.  - Remove the prepareStatement method from ConectaDB so as not to interfere with the instance between the two objects.

public class Usuario {

    private int id;
    private String nickName;
    private String password;
    private String Email;
    private ConectaDB conexion;

    public Usuario(int id, String nickName, String password, String email) {
        this.id = id;
        this.nickName = nickName;
        this.password = password;
        Email = email;
    }

    public ArrayList<Usuario> getUsuarios() {
        Connection con = null;
        con = conexion.conecta();
        ArrayList<Usuario> Usuarios = new ArrayList();

        try {
            PreparedStatement getData = con.prepareStatement("SELECT IDUsuario, Nickname, Password, Email FROM usuario");
            ResultSet data;
            data = getData.executeQuery();
            while (data.next()) {
                id = data.getInt(1);
                nickName = data.getString(2);
                password = data.getString(3);
                Email = data.getString(4);
                Usuario usser = new Usuario(data.getInt(1), data.getString(2), data.getString(3), data.getString(4));
                Usuarios.add(usser);
            }
            return Usuarios;
        } catch (SQLException e) {
        }
        return Usuarios;
    }
}

and

public class ConectaDB {

    public static Connection conecta(){

        Connection conecta=null;

        try{
            Class.forName("com.mysql.jdbc.Driver");
            String servidor="jdbc:mysql://xxxxxx:xxxx/bbdd_g1"; //conectamos a nuestra propia maquina
            String usuario="admin_g1";
            String password="a7586";
            //inicializamos objeto conecta, del tipo connection
            conecta = DriverManager.getConnection(servidor, usuario, password);

        }catch(ClassNotFoundException e)
        {
            System.out.println(e.getMessage());
        }
        catch(Exception e) //capturar el resto de exceptions
        {
            System.out.println(e.getMessage());
        }finally{
            return conecta;//como el default de los case, pero se ejecuta si o si
        }

    }

    public static PreparedStatement preparedStatement(Connection con ,String sql) throws SQLException {
        return con.prepareStatement(sql);
    }
}
    
answered by 16.04.2018 / 09:27
source
0

Why ...?

 PreparedStatement getData = conexion.preparedStatement("SELECT IDUsuario, Nickname, Password, Email FROM usuario");           

When ...

  con = conexion.conecta();
    
answered by 16.04.2018 в 09:27