Curso de Java Netbeans Completo☕ [02.- Conectar tabla(JTable) con mysql (parte 1)]

En este tutorial vamos a crear una conexion de java con mysql para posteriormente llenar nuestra (JTable) con los datos d enuestra trabla de mysql.

Java swing: https://es.wikipedia.org/wiki/Swing_(biblioteca_gr%C3%A1fica)
Documentación de java: https://docs.oracle.com/javase/8/docs/api/

Codigo: https://github.com/programadornovato/JavaGUI/commit/35828ba3b5c3611cd42b582d5e3af3fec447ed4d

package com.programadornovato.javagui;

import javax.swing.JOptionPane;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author eugenio
 */
public class Formulario extends javax.swing.JFrame {

    Connection con;
    String driver="com.mysql.cj.jdbc.Driver";
    String user="eugenio";
    String pass="123456";
    String url="jdbc:mysql://localhost:3306/empleados?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
    public void conectar(){
        con=null;
        try {
            Class.forName(driver);
            con=(Connection) DriverManager.getConnection(url,user,pass);
            if(con!=null){
                estadoCon.setText("Conexion exitosa");
            }
        } catch (Exception e) {
            estadoCon.setText("Conexion no exitosa "+e);
        }
    }
    /**
     * Creates new form Formulario
     */
    public Formulario() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        estadoCon = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Probar conexion");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(estadoCon, javax.swing.GroupLayout.PREFERRED_SIZE, 345, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addContainerGap(43, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addGap(27, 27, 27)
                .addComponent(estadoCon, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(208, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        conectar();
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Formulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Formulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Formulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Formulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Formulario().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel estadoCon;
    private javax.swing.JButton jButton1;
    // End of variables declaration//GEN-END:variables
}
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Base de datos: `empleados`
--

-- --------------------------------------------------------

--
-- Estructura de tabla para la tabla `empleados`
--

CREATE TABLE `empleados` (
  `id` int(5) NOT NULL,
  `nombre` varchar(100) NOT NULL,
  `puesto` varchar(100) NOT NULL,
  `edad` int(5) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Volcado de datos para la tabla `empleados`
--

INSERT INTO `empleados` (`id`, `nombre`, `puesto`, `edad`) VALUES
(3, 'rosio', 'archivo', 25),
(25, 'elena', 'archivo', 28);

--
-- Índices para tablas volcadas
--

--
-- Indices de la tabla `empleados`
--
ALTER TABLE `empleados`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT de las tablas volcadas
--

--
-- AUTO_INCREMENT de la tabla `empleados`
--
ALTER TABLE `empleados`
  MODIFY `id` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=33;
COMMIT;

[Curso] Java Netbeans GUI Completo☕: https://www.youtube.com/watch?v=S0XKc_MJCS0&list=PLCTD_CpMeEKThfXo8D-RXOGu5FarO7_qv

? Instalar Netbeans 11 en Windows 10: https://www.youtube.com/watch?v=EouitrKS6Cw
? Instalar Netbeans 11 en Ubuntu con Snap [Más fácil que en windows?]: https://www.youtube.com/watch?v=LllPPV9SMzQ
? Descargar e Instalar Netbeans 11 en ubuntu 18 04: https://www.youtube.com/watch?v=tWiX3Z5t5kQ
? Netbeans Sublime Theme ?: https://www.youtube.com/watch?v=oAF2Q7mTZZM
? Editar CSS directamenete en Chrome con Netbeans: https://www.youtube.com/watch?v=HlQs0a7R2cY
Pagina de netbeans: https://netbeans.org/

Instalar MySQL? en Ubuntu 18.04: https://www.youtube.com/watch?v=hx-nGKFVixA
Instalar PhpMyAdmin en Windows 10 ⛵: https://youtu.be/36ritPuyd00
Gracias por apoyar este canal: https://www.patreon.com/programadornovato?fan_landing=true

? Facebook: https://facebook.com/ProgramadorNovatoOficial
? Twitter: https://twitter.com/programadornova
? Linkedin: https://www.linkedin.com/in/programadornovato/
? Instagram: https://www.instagram.com/programadornovato/

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *