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

Asked

Viewed 244 times

3

Classe Fabrica

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(Home.java:10)

2 answers

3


The correct thing would be to initialize conn in your DAO controller. This code does not work because it (conn) is null. Only instantiated in the method insert() but not in the select().

Once the connection is already created you can remove the other points where you did manually. Always prefer to capture the more specific and not more generic Exception. I suggest reading some questions from tag Exception

see the section of the():

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 flame must stay:

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

Recommended reading:

How Try-with-Resources works?

There is some drawback in always catching Exception and not something more specific?

Best way to deal with Exceptions

How to best treat exceptions in Java?

What is addiction injection?

What are the differences between Dependency Injection and Control Inversion?

  • Thank you, you helped me a lot!

2

Complementing the @rray response, if you don’t want to have to pass the connection every time you instantiate a Hallucination can do so:

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

Hallucination (Constructor) You can then use conn in all Alunodao methods.:

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

Calling for:

AlunoDAO dao = new AlunoDAO();
  • Thanks! I got it, by putting the Conn = Fabrica.getConexao(); no select().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.