Connection to database - MySQL and Java

8

I already have a local server on my machine (localhost) with MySQL running normally. From there, I would like to connect my database with Java, but ... how do I do this? Is there a Swing component that displays the fields of a given MySQL table?

I'm creating a program for my partner's desktop. That is, it's another PC! Does the database still connect? Is internet needed?

    
asked by anonymous 13.05.2015 / 20:10

1 answer

13

I will try to give a summary of how to start an application with database using JDBC: The first step is to create the connection class, we can create it as follows:

public class Conexao {

    private static final String USUARIO = "root";
    private static final String SENHA = "";
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/meubanco";
    private static final String DRIVER = "com.mysql.jdbc.Driver";

    // Conectar ao banco
    public static Connection abrir() throws Exception {
        // Registrar o driver
        Class.forName(DRIVER);
        // Capturar a conexão
        Connection conn = DriverManager.getConnection(URL, USUARIO, SENHA);
        // Retorna a conexao aberta
        return conn;


    }

}

The previous method returns the open connection, remembering that you need to add the Connector / J which is the driver responsible for connecting java to Mysql, you can download the driver in that LINK . After downloading it go into your project, click on the Libraries folder / Add JAR ... Look for your driver and click add, this in Netbeans. If you are using Eclipse Click on your project and go to Build Path / Configure Build Path and then look for the Libraries tab, click the Add External Jars option and select the Driver.

Part 2: I will try to simplify this explanation so that it is not too extensive, it will be up to you to study more about it later. Let's start with the Client Class

public class Cliente {

    private Integer codigoCliente;
    private String nomeCliente;
    private Integer idadeCliente;

    public Integer getCodigoCliente() {
        return codigoCliente;
    }

    public void setCodigoCliente(Integer codigoCliente) {
        this.codigoCliente = codigoCliente;
    }

    public String getNomeCliente() {
        return nomeCliente;
    }

    public void setNomeCliente(String nomeCliente) {
        this.nomeCliente = nomeCliente;
    }

    public Integer getIdadeCliente() {
        return idadeCliente;
    }

    public void setIdadeCliente(Integer idadeCliente) {
        this.idadeCliente = idadeCliente;
    }

}

Now you need a class that interacts with the Database, this class is usually assigned the name DAO which is part of the DAO pattern () Assuming you already have saved information in the database and just want to return them in a table I'll just do the method that does the search for this data:

public class ClienteDAO {

    public List<Cliente> buscar(Cliente c) throws Exception {
        /* Define a SQL */
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT cod_cliente, nome_cliente, idade_cliente ");
        sql.append("FROM tabela_cliente ");
        sql.append("WHERE nome_cliente LIKE ? ");
        sql.append("ORDER BY nome_cliente ");

        /* Abre a conexão que criamos o retorno é armazenado na variavel conn */
        Connection conn = Conexao.abrir();

        /* Mapeamento objeto relacional */
        PreparedStatement comando = conn.prepareStatement(sql.toString());
        comando.setString(1, "%" + c.getNomeCliente()+ "%");

        /* Executa a SQL e captura o resultado da consulta */
        ResultSet resultado = comando.executeQuery();

        /* Cria uma lista para armazenar o resultado da consulta */
        List<Cliente> lista = new ArrayList<Cliente>();

        /* Percorre o resultado armazenando os valores em uma lista */
        while (resultado.next()) {
            /* Cria um objeto para armazenar uma linha da consulta */
            Cliente linha = new Cliente();
            linha.setCodigoCliente(resultado.getInt("cod_cliente"));
            linha.setNomeCliente(resultado.getString("nome_cliente"));
            linha.setIdadeCliente(resultado.getInt("idade_cliente"));
            /* Armazena a linha lida em uma lista */
            lista.add(linha);
        }

        /* Fecha a conexão */
        resultado.close();
        comando.close();
        conn.close();

        /* Retorna a lista contendo o resultado da consulta */
        return lista;
    }

    }

Part 3: Now we have the DAO (ClientDAO) and the MODEL (Client) now in your view (view) vo adds a Painel de Rolagem and within that panel you put a Tabela in such a way:

Nextyourightclickonyourtable,gotoproperties,searchforModelclickon...and%on%selectDefinirPropriedades...andenterthefollowingcode:newClientTableModel()andignoretheerror,becausewewillsolveinthenextstep.Example:

Step 4 (Last) We need one more Class, this class is the same as we instantiated in our Código Personalizado just above.

public class ClienteTableModel extends AbstractTableModel {
    /* Lista para armazenar os cabeçalhos da tabela */

    private Vector colunas;

    /* Lista para armazenar os dados da tabela */
    private Vector linhas;

    public ClienteTableModel() {
        /* Definição das colunas da tabela */
        colunas = new Vector();
        colunas.add("Código");
        colunas.add("Nome");
        colunas.add("Idade");

        /* Definição dos dados da tabela */
        linhas = new Vector();
    }

    public int getRowCount() {
        /* Captura o total de linhas da tabela */
        int totalLinhas = linhas.size();

        /* Retorna o total de linhas */
        return totalLinhas;
    }

    public int getColumnCount() {
        /* Captura o total de colunas da tabela */
        int totalColunas = colunas.size();

        /* Retorna o total de colunas */
        return totalColunas;
    }

    public String getColumnName(int coluna) {
        /* Captura o nome da coluna */
        String nomeColuna = (String) colunas.get(coluna);

        /* Retorna o nome da coluna */
        return nomeColuna;
    }

    public Object getValueAt(int linha, int coluna) {
        /* Captura o registro informado */
        Vector registro = (Vector) linhas.get(linha);

        /* Dentro do registro captura a coluna selecionada */
        Object dado = registro.get(coluna);

        /* Retorna o valor capturado */
        return dado;
    }

    public void adicionar(List<Cliente> lista) {
        /* Reinicializa os dados da tabela */
        linhas = new Vector();

        /* Percorre a lista copiando os dados para a tabela */
        for (Cliente d : lista) {
            Funcionario f = new Funcionario();
            /* Cria uma linha da tabela */
            Vector<Object> linha = new Vector();
            linha.add(d.getCodigoCliente());
            linha.add(d.getNomeCliente());
            linha.add(d.getIdadeCliente());
            /* Adiciona a linha a tabela */
            linhas.add(linha);
        }
        /* Atualiza a tabela */
        fireTableDataChanged();
    }

}

This code is responsible for populating the table, but a detail is still missing. How to update the table, ie how to load the data. I do it as follows: in the beginning of the code of your screen, after the constructor add a method called update as follows:

  public NewJFrame() {
        initComponents();
    }

After the builder adds:

public void atualizar(){
         try{
             /* Criação do modelo */
            Cliente d = new Cliente();

            /* Criação do DAO */
            ClienteDAO dao = new ClienteDAO();
            List<Cliente> lista = dao.buscar(d);

            /* Captura o modelo da tabela */
            ClienteTableModel modelo = (ClienteTableModel)jTable1.getModel();

            /* Copia os dados da consulta para a tabela */
            modelo.adicionar(lista);

        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(null, "Erro ao tentar buscar um Cliente");
        }
    }

And then click on your JTable and add a tela(jFrame) event and within that event do the following:

  private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  

        atualizar();

        //Opcional
        setLocationRelativeTo(null);
        setResizable(false);

    } 

And now your application is ready to load the database data into a table. I'm sorry if the explanation was not very good, or if it got very extensive, I do not think I have much of the "gift" to explain. Good luck with the codes and study hard.

    
13.05.2015 / 22:07