I'm having trouble trying to list data from a mysql table

3

Manufacturing Class

import java.sql.Connection;
import java.sql.DriverManager;


public class Fabrica {

    public  Connection getConexao() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");

            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/teste", "root", "123");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

}

AlunoDAO Class

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AlunoDAO {

private Connection conn;

    public void insert(String nome, int matricula) {
        String sql = "insert into aluno values (?,?)";
        conn = new Fabrica().getConexao();

        try {

            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, nome);
            ps.setInt(2, matricula);          
            ps.execute();
            ps.close();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                conn.close();
            } catch (SQLException ex) {
               Logger.getLogger(AlunoDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void select() {
        String sql = "select * from aluno";

        try {


            PreparedStatement ps = this.conn.prepareStatement(sql); //linha 41

            ResultSet result = ps.executeQuery();
            while(result.next()) {
                System.out.println(result.getString("nome"));
                System.out.println(result.getInt("matricula"));
            }              
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

MAIN Class

public class Principal {
    public static void main(String[] args) {      
        AlunoDAO dao = new AlunoDAO();


        dao.select(); //linha 10
    }
}
  

ERROR:   java.lang.NullPointerException

     

at AlunoDAO.select (AlunoDAO.java:41)

     

at Principal.main (Principal.java:10)

    
asked by anonymous 19.09.2017 / 22:45

2 answers

3

The most correct would be to initialize conn in the constructor of your DAO. This code does not work because it ( conn ) is null. It is only instantiated in insert() method but not select() .

Once the connection has already been created you can remove the other points where you did it manually. Always prefer to capture the more specific exception and not more generic. I suggest reading some tag exception

see the insert () section:

public void insert(String nome, int matricula) {
    String sql = "insert into aluno values (?,?)";
    conn = new Fabrica().getConexao(); //<--Aqui, pega a conexão o que não acontece no select

Solution:

public class AlunoDAO {
  private Connection conn;
  public void AlunoDAO(Connection conn){
    conn = conn;
  }

The call should be:

AlunoDAO dao = new AlunoDAO(new Fabrica().getConexao());

Recommended reading:

How does try-with-resources work?

Are there any drawbacks in always catching Exception and not something more specific?

Best way to handle Exceptions

How best to handle exceptions in Java?

What is dependency injection?

What are the differences between Dependency Injection and Control Inversion?

    
19.09.2017 / 22:48
2

Complementing the response of @rray, if you do not want to have to pass the connection every time you instantiate a Student you can do this:

Factory :

public class Fabrica {

    public static Connection getConexao() {
        static Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");

            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/teste", "root", "123");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
}

AlunoDAO (Constructor) You can then use conn in all AlunoDAO methods.

public class AlunoDAO {
  private Connection conn;
  public void AlunoDAO(){
    conn = Fabrica.getConexao();
  }

Call :

AlunoDAO dao = new AlunoDAO();
    
19.09.2017 / 23:03