Nullpointerexception in database connection

Asked

Viewed 121 times

1

Anyway, I’m getting one nullpointerException just that I have no idea how to deal with it, I took a look on the net about and apparently the problem is in uninitiated variables and things like that, but I’m sure it’s all been initialized here.

Stack Trace

Servlet:

public ControllerLivros() {
    super();
    // TODO Auto-generated constructor stub
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    //doGet(request, response);
    request.setCharacterEncoding("UTF-8");
    String nomeAutor = request.getParameter("nomeAutor");
    String nomeLivro = request.getParameter("nomeLivro");
    String nomeGenero = request.getParameter("nomeGenero");

    if(nomeAutor == null || nomeAutor.trim().equals("") || nomeAutor.trim().equals("null")) {
        request.setAttribute("autorNull", "O autor não pode ser em branco:");
        request.getRequestDispatcher("Livros.jsp").forward(request, response);
    }
    if(nomeLivro == null || nomeLivro.trim().equals("") || nomeLivro.trim().equals("null")) {
        request.setAttribute("livroNull", "O nome do livro não pode ser em branco:");
        request.getRequestDispatcher("Livros.jsp").forward(request, response);
    }
    if(nomeGenero == null) {
        request.setAttribute("generoNull", "O genero não foi escolhido:");
        request.getRequestDispatcher("Livros.jsp").forward(request, response);
    }


    Livros livro = new Livros(1, nomeLivro, nomeGenero, nomeAutor);

    insertLivros.insertLivro(livro);


    PrintWriter teste = response.getWriter();


    request.setAttribute("nomeAutor", nomeAutor);
    request.setAttribute("nomeLivro", nomeLivro);


}

class Insert:

public class insertLivros {

public static void insertLivro(Livros livro) {


    Connection connection = null;
    PreparedStatement pstmt = null;

    try {
        String query = null;
        query = "insert into livros(nomelivro, nomegenero, nomeautor) VALUES(?, ?, ?)";

    //Statement statement = null;

    connection = Conexao.getConexao();
    pstmt = connection.prepareStatement(query);
    pstmt.setString(1, livro.getNomeLivro());
    pstmt.setString(2, livro.getNomeGenero());
    pstmt.setString(3, livro.getNomeAutor());


    pstmt.executeUpdate();
    connection.close();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    }

}

connection class (do not believe the error is here)

public class Conexao {

public static java.sql.Connection getConexao(){

    Connection connection = null;

        String driver = "com.mysql.jdbc.Driver";
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }


        String user = "root";
        String senha = "guimazx33";
        String url = "jdbc:mysql://localhost/aula";

        try {
        connection = DriverManager.getConnection(url, user, senha);
        return connection;

        }catch (SQLException e) {
         System.out.println("nao conectou");
    }
        return connection;
        }
}
  • remembering that if I create a class with a main and instantiate an object and ask for an Insert, it works, but by Servlet it does not work well.

1 answer

1


The error is not well in the code, but the code is wrong precisely because it hides the error. So it improves and at least treats the error properly. The failure in connection you will have to see why it occurs.

public class insertLivros {
    public static void insertLivro(Livros livro) {
        try {
            Connection connection = Conexao.getConexao();
            PreparedStatement pstmt = connection.prepareStatement("insert into livros(nomelivro, nomegenero, nomeautor) VALUES(?, ?, ?)");
            pstmt.setString(1, livro.getNomeLivro());
            pstmt.setString(2, livro.getNomeGenero());
            pstmt.setString(3, livro.getNomeAutor());
            pstmt.executeUpdate();
        } finally {
            connection.close();
        }
    }
}

public class Conexao {
    public static Connection getConexao(){
        Class.forName("com.mysql.jdbc.Driver"); //não sei se isto é necessário
        return DriverManager.getConnection("root", "guimazx33", "jdbc:mysql://localhost/aula");
    }
}

I put in the Github for future reference.

It is obvious that the error will need to be dealt with, but handling the error is different from hiding it, which is what is occurring in the code. I won’t try to treat because I don’t know what the goal is. I could even capture an exception to launch a more significant one, or I could turn into error code, what a lot of people don’t like, especially in Java, or would only deal with the error in the class that takes care of user interaction.

My codes usually have one or the other catch in the whole application, I don’t know why I see people’s codes a catch in every method, it makes no sense.

To tell the truth I have serious doubts if the class Conexao has some function.

  • Dude I made the changes as you indicated there, honestly it works and I don’t quite understand why, I’ll keep looking. Obs:I’m just sorry I can’t get up there in reputation, I’m new not yet released.

  • Blz, when you have 15 points you can go back and vote.

Browser other questions tagged

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