Error: java.lang.NullPointerException in project using JDBC

0

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();
    }       
}
    
asked by anonymous 15.11.2017 / 19:37

1 answer

0

Let's change a detail in your ConnectionFactory :

public class ConnectionFactory {
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(
                    "jdbc:mysql://localhost/fj21?useSSL=false", "root", "");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }   
}

The detail is that modifier static more.

Now your ConnectionTeste class suffers a change:

public class ConnectionTeste {
    public static void main(String[] args) {
        try (Connection connection = ConnectionFactory.getConnection()) {
            System.out.println("Conexão aberta!");
        }
    }
}

So let's redo your DAO:

public class ContatoDao {

    private static final String INSERT_SQL = ""
            + "INSERT INTO Contatos"
            + "(nome, email, endereco, dataNascimento)"
            + "VALUES (?, ?, ?, ?)";

    private static final String SELECT_SQL = "SELECT * FROM Contatos";

    public void adiciona(Contato contato) {
        // String sql = INSERT_SQL;  
    }

    public List<Contato> getLista() {
        try (
            Connection c = ConnectionFactory.getConnection();
            PreparedStatement stmt = c.prepareStatement(SELECT_SQL);
            ResultSet rs = stmt.executeQuery();
        ) {
            List<Contato> contatos = new ArrayList<>();
            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);
            }
            return contatos;
        } catch(SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

Your TestaLista class remains almost the same:

public class TestaLista {

    public static void main(String[] args) {
        ContatoDao dao = new ContatoDao();
        List<Contato> contatos = dao.getLista();

        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") ;
        }
    }
}

Please note that I've used the try-with-resources in all cases.

I also recommend using the class LocalDate instead of Calendar to represent dates.

    
15.11.2017 / 21:50