I am trying to generate a ArrayList
users from a DB
, the case is that when executing the PreparedStatement
it returns a NullPointer
and tells me that the connection object is null, it is something that does not happen to me in other statements that I have and they work.
I leave the code of Array
the and the code of the 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 Connect 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!
Even though we don't see the object declaration
conexion
, it looks like it's giving you a NullPointer because you're not accessing the object with the connection.The connection is in
con
but the preparedStatement is taken 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 connection method preparedStatement to do the prepareStatement, but surely you should choose one of the following strategies. - Make a static method that prepares the query for you, passing the connection to it. - Make ConectaDB an object that saves the connection and you only pass the query to it. - Remove the prepareStatement method from ConectaDB so as not to mess with the instance between the two objects.
Y
Why...?
When...