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!