Could help me with the error below, this is one, I'm having error in lines 14 of class TestaLista and error in line 32 of 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 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);
}
}
}
The connection classes follow:
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();
}
}