0
Could help me with the error below, it is a, I have error in lines 14 of the class Testalista and error in line 32 of the class ContatoDao
.
Exception in thread "main" java.lang.NullPointerException at br.com.caelum.jdbc.dao.ContatoDao.getLista(ContatoDao.java:28) at br.com.caelum.jdbc.teste.TestaLista.main(TestaLista.java:14)
Class TestaLista
:
public class TestaLista {
public static void main(String[] args) throws RuntimeException{
ContatoDao dao = new ContatoDao();
List<Contato> contatos = dao.getLista(); // <-- Aponta erro nessa parte
for(Contato contato : contatos) {
System.out.println("Nome: " + contato.getNome());
System.out.println("Email: " + contato.getEmail());
System.out.println("Endereço: " + contato.getEndereco());
System.out.println("Data de Nascimento: " +
contato.getDataNascimento().getTime() + "\n") ;
}
}
}
Class ContatoDao
, with error in the PreparedStatement
:
public class ContatoDao {
private Connection connection;
public void adiciona(Contato contato) {
String sql = "insert into contatos" +
"(nome, email, endereco, dataNascimento)" +
"values(?,?,?,?)";
}
public List<Contato> getLista(){
try {
List<Contato> contatos = new ArrayList<Contato>();
PreparedStatement stmt = this.connection
.prepareStatement("select * from contatos"); // <-- Aponta erro nessa parte...
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
//Objeto contato
Contato contato = new Contato();
contato.setId(rs.getLong("id"));
contato.setNome(rs.getString("nome"));
contato.setEmail(rs.getString("email"));
contato.setEndereco(rs.getString("endereco"));
//montando a data com Calendar
Calendar data = Calendar.getInstance();
data.setTime(rs.getDate("dataNascimento"));
contato.setDataNascimento(data);
contatos.add(contato);
}
rs.close();
stmt.close();
return contatos;
}catch(SQLException e) {
throw new RuntimeException(e);
}
}
}
Follow the connection classes:
public class ConnectionFactory {
public Connection getConnection() {
try {
return DriverManager.getConnection(
"jdbc:mysql://localhost/fj21?useSSL=false", "root", "");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
Class ConnectionTeste
:
public class ConnectionTeste {
public static void main(String[] args) throws SQLException {
Connection connection = new ConnectionFactory().getConnection();
System.out.println("Conexão aberta!");
connection.close();
}
}
Your connection may be null, always make sure to start the connection before creating a Statement.
– user28595
Without looking right and even without having enough information I think I can say that the problem is lack of initialization of
connection
.– Maniero
Possible duplicate of I’m having trouble trying to list data from a mysql table
– user28595
@Articuno the link you passed helped in some fixes but I still have the same problem :/
– Thiago Pernomian
If you don’t start the connection, the problem will never be solved anyway.
– user28595
See also: https://answall.com/q/172909/132
– Victor Stafusa