Include BD data in Java

Asked

Viewed 86 times

1

I’m following a distance course, only I’m having trouble including the record. It does not include, but it also does not present any error, and by the examples of the teacher I followed, it did not work. I’ve also seen several video lessons on the Internet and handouts, but still not included in the comic.

NOTE: I already tested the connection with the BD and everything is OK.

Class Connection to the BD:

    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 receiving the 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 calling methods and executing:

public class TestaAluno {

    public static void main(String[] args) {

        Alunos al = new Alunos();

        al.incluir();

    }

1 answer

2


You are not managing the connection and the PreparedStatement in appropriate ways, and is dropping them open. Use the syntax Try-with-Resources Java 7+ to solve this in the simplest way.

Do so:

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 seen that maintaining public attributes is bad programming practice, isn’t it? So please don’t do this.

Ah yes, and make sure that the Mysql Connector JAR is on your classpath.

  • 1

    'Eagle eyes' medal successfully unlocked.

  • I really had not tried for public attributes, although I have already seen it in my course. Now I am in error:
java.sql.SQLException: No suitable driver found for jdbc:mysql://127.0.0.1/alunos
 at java.sql.DriverManager.getConnection(DriverManager.java:689)
 at java.sql.DriverManager.getConnection(DriverManager.java:247)
 at br.com.curso.ConexaoAluno.conexao(ConexaoAluno.java:18)
 at br.com.curso.Alunos.incluir(Alunos.java:18)
 at br.com.curso.TestaAluno.main(TestaAluno.java:8)

  • @Itallofreire I updated my answer as Class.forName. What a mistake it is now?

  • In the debug he says it contains error on line 17: throw new ExceptionInInitializerError("Nao foi possivel achar o Driver do SQL." + e);

  • @Itallofreire Bingo! It was exactly the mistake I expected it would make. Your problem is that the mysql-Connector jar is not in your classpath. I put the download link at the end of the reply.

  • @Victorstafusa so I went in libraries and add mysql-Connector-java-5.1.35.zp within the java build path, That wouldn’t solve my problem ?

  • 1

    @Itallofreire It has to be .jar. Put .zip won’t work. Anyway, you can see what your IDE generates exactly when running the program?

  • 1

    @Perfect Victorstafusa had no attempt for that detail. Very obg, helped a lot

  • Um... shouldn’t have the :3306 on the way to the bank?

Show 4 more comments

Browser other questions tagged

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