Database connection - Mysql and Java

Asked

Viewed 27,206 times

9

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 that? Is there any Swing component that displays the fields of a particular Mysql table?

I’m creating a program for my partner’s desktop. I mean, it’s another PC! Does the database still connect? Do you need internet?

  • There is, the most used is jTable, where the data is loaded into a table

  • If your friend wants to connect in the database that is on your machine I think the best way is to create a fixed ip and configure the connection with that ip

  • Thanks! But... you could give me an example code?

  • On the Netbeans website there is a brief tutorial teaching you how to do this. Try to study it and do it, if you have any other questions regarding any more specific point of the tutorial, post so that we can help you: https://netbeans.org/kb/docs/ide/mysql_pt_BR.html

  • I’m making an explanation, just a moment

1 answer

15

I will try to give a brief of how to start a database application 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 that is the driver responsible for connecting the java to Mysql, Voce can download the driver in this LINK. After downloading it go to your project, click the Libraries/Add JAR folder... Look for your driver and click Add, this in Netbeans. If you’re using Eclipse Click on your project and go to Build Path/Configure Build Path and then look for the Libraries tab, click on the Add External Jars option and select the Driver.


Second part: I will try to simplify this explanation as much as possible so that it does not get too extensive, it will be up to the Voce to study more on the subject later. Let’s start with Customer 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, usually this class has assigned the name DAO which is part of the DAO standard (Data Access Object) Assuming Voce already has information saved in the database and just wants to return it in a table I will only do the method that searches 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;
    }

    }

3rd part: Ready we have DAO(Clientedao) and MODEL(Client) now in your view(Screen) vo adds a Painel de Rolagem and inside that panel Voce places a Tabela getting so:

inserir a descrição da imagem aqui

Then right-click on your table, go to properties, search for Model click on ... and Definir Propriedades... select Código Personalizado and enter the following code: new Clientetablemodel() and ignore the error, as we will solve it in the next step. Example:

inserir a descrição da imagem aqui


Fourth step (Last step) We need one more Class, that class is the same one we instancimos in our JTable 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 filling the table, but there is still one detail missing. How to update the table, that is, how to load the data. I do it this way: at the beginning of your screen code, after the constructor add a method called update as follows:

  public NewJFrame() {
        initComponents();
    }

After the constructor 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 tela(jFrame) and add an event Window/WindowOpened and within that event do the following:

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

        atualizar();

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

    } 

And ready, 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 was too extensive, I guess I don’t have much of a "gift" to explain. Good luck with the codes and study hard.

  • I’m having trouble with this line of code: public List<Funcionario> buscar(Funcionaio f) throws Exception: the IDE says: type List does not take paramenters

  • @alexjosesilva see if you have done the List import correctly. Java.util.list

  • I did everything like this written here...but the error remains

Browser other questions tagged

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