Include data in the DB in Java

1

I'm following a distance course, but I'm having trouble logging in. It does not include, but also does not present any error, and by the examples of the teacher that I followed, did not work. I have also seen several videotapes on the Internet and handouts, but still still not included in the DB.

NOTE: I have already tested the DB connection and everything is OK.

Connection class with DB:

    public Statement stm; // Prepara e realiza pesquisas no BD.
    public ResultSet rs; // Armazena o resultado de uma pesquisa passada para o STM.
    private String driver = "com.mysql.jdbc.Driver"; // Identificar o BD.
    private String caminho = "jdbc:mysql://127.0.0.1/alunos"; // Seta o local do BD.
    private String usuario = "root";
    private String senha = "";
    public Connection conn; // Realiza a conexao com o BD.


    public void conexao(){ // Metodo que realizar conexao com o BD.
        try {
            System.setProperty("jdbc.Drivers", driver); // Seta a propriedade do driverde conexao
            conn = DriverManager.getConnection(caminho, usuario, senha); // Realizao conexao com o BD.
            System.out.println("Conectado com Sucesso!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void desconecta(){ // Metodo para fechar conexao BD.
        try {
            conn.close(); // Fecha conexao.
        } catch (SQLException e) {
            e.printStackTrace();
        }

Class that receives methods:

public class Alunos {

    ConexaoAluno conecta = new ConexaoAluno();  // Variavel global.

    public void incluir(){

        conecta.conexao();

        try {
            PreparedStatement pst = conecta.conn.prepareStatement("insert into alunos (endereco, cep, cidade, estado, pais) values(?,?,?,?,?)");
            pst.setString(1, "Av. Mantiqueira");
            pst.setString(2, "74565-410");
            pst.setString(3, "Goiania");
            pst.setString(4, "GO");
            pst.setString(5, "Brasil");
            pst.executeUpdate();
            System.out.print("Inserido com sucesso!");
        } catch (SQLException e) {
            e.printStackTrace();
        }       

Class that calls methods and executes:

public class TestaAluno {

    public static void main(String[] args) {

        Alunos al = new Alunos();

        al.incluir();

    }
    
asked by anonymous 12.06.2015 / 19:18

1 answer

2

You are not managing the connection and PreparedStatement in proper ways, and you are leaving them open. Use the try-with-resources syntax of Java 7+ to solve this in the simplest way.

Do this:

public class ConexaoAluno {
    private static final String driver = "com.mysql.jdbc.Driver";
    private static final String caminho = "jdbc:mysql://127.0.0.1/alunos";
    private static final String usuario = "root";
    private static final String senha = "";

    static {
        System.setProperty("jdbc.Drivers", driver);
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new ExceptionInInitializerError("Erro fatal. Não foi possível achar o driver do MySQL", e);
        }
    }

    public Connection conexao() throws SQLException {
        return DriverManager.getConnection(caminho, usuario, senha);
    }
}
public class Alunos {

    private static final String INCLUIR_SQL = "INSERT INTO alunos (endereco, cep, cidade, estado, pais) VALUES (?, ?, ?, ?, ?)";

    private final ConexaoAluno conecta;

    public Alunos() {
        conecta = new ConexaoAluno();
    }

    public void incluir() {
        try (Connection conn = conecta.conexao(),
            PreparedStatement pst = conn.prepareStatement(INCLUIR_SQL))
        {
            pst.setString(1, "Av. Mantiqueira");
            pst.setString(2, "74565-410");
            pst.setString(3, "Goiania");
            pst.setString(4, "GO");
            pst.setString(5, "Brasil");
            pst.executeUpdate();
            System.out.print("Inserido com sucesso!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
public class TestaAluno {
    public static void main(String[] args) {
        Alunos al = new Alunos();
        al.incluir();
    }
}

And another thing, you may have noticed that maintaining public attributes is a bad programming practice, is not it? So please do not do this.

Oh yeah, and certify is that the MySQL Connector JAR is in your classpath.

    
12.06.2015 / 19:34