manual de conexión entre java netbeans y mysql

Upload: alfredo-tamayo

Post on 05-Mar-2016

252 views

Category:

Documents


2 download

DESCRIPTION

topicos de base de datos

TRANSCRIPT

Manual de conexin entre Java NetBeans y MySQLLa finalidad de este tutorial es explicar la forma de realizar una conexin entre el lenguaje de programacin Java (IDE NetBeans) y la base de datos de SQL.

Software Necesario1. Java NetBeans2. phpMyAdmin3. Conector (mysql-connector-java-5.1.22)

Despus de instalar el phpMyAdmin, procedemos a ejecutarlo; para esto abrimos un explorador de internet (Mozilla, Explorer, Google Chrome, etc) y en la direccin tecleamos la ruta para direccionarnos a nuestro servidor local:http://localhost/phpMyAdmin/Si no entra 127.0.0.1/phpMyAdmin

Capturamos nombre de usuario y passwordY hecho esto nos aparecer nuestro servidor local en phpMyAdmin

Vamos a crear una base de datos en la opcin Databases

La base de datos la llamaremos DBfacturacion.

Despus vamos a crear la tabla de clientes (con 5 campos)

Aparecer la siguiente ventana, donde capturaremos los campos

Al seleccionar la base de datos (DBfacturacion), podemos ver la tabla incorporada en la base

Agregamos el campo gnero

Esto lo que tenemos que hacer aqu, ahora necesitamos ir al programa Java NetBeans

Necesitamos crear un proyecto nuevo

El proyecto lo nombraremos: Facturacion y antes de terminar quitamos la seleccin de: Crear clase principal y Configurar como proyecto principal. (No olvides seleccionar la carpeta creada: FacturacionJava)

Y listo, ya est creado

Ahora ser necesario crear en paquete de fuentes dos paquetes nuevos, uno llamado BaseDatos y otro Formularios. No son ms que dos carpetas que nos permiten organizar el proyecto.

Ahora necesitaremos agregar el conector que nos servir para enlazar los formularios de Java con el servidor SQL (mysql-connector-java-5.1.22)Lo primero que necesitamos hacer es pegarlo en la carpeta que creamos para el proyecto (c:/facturacionJava/facturacion)

Ahora necesitamos agregar ese elemento al proyecto en bibliotecas

Seleccionamos la carpeta correcta y el constructor

Ahora en el paquete de BaseDatos, vamos a crear una clase que nos permitir la conexin (esta clase puede ser genrica dado que siempre es la misma, lo nico que cambia es el nombre de la base de datos, y puede ser usuario y contrasea)

Lo primero que tenemos que hacer es agregar las libreras que vamos a utilizar//Librerasimport java.sql.*;import javax.swing.JOptionPane;

Hecho esto vamos agregar las variables tipo String que nos permitirn especificar caractersticas de la conexin, dentro de la clase pblica ConexionMySQL.

public class ConexionMySQL { //Variables para conexin public String db = "BDfacturacion"; public String url = " jdbc:mysql://localhost/"+db; public String user = "root"; public String pass = "1234";}

Debajo creamos un constructor vaco por si se requiere

//Constructor public ConexionMySQL(){ }

Debajo del constructor vamos a crear un mtodo que llamaremos Conectar

//Mtodo para conexin public Connection Conectar(){ Connection link= null; try{ //cargamos el driver MySQL Class.forName("org.gjt.mm.mysql.Driver"); //Creamos enlace hacia la base de datos link = DriverManager.getConnection(this.url,this.user,this.pass); }catch(Exception e){ JOptionPane.showMessageDialog(null, e); } return link; }

Cdigo completo de la clase conectora

package BaseDatos;

//Librerasimport java.sql.*;import javax.swing.JOptionPane;

public class ConexionMySQL { //Variables para conexin public String db = "BDfacturacion"; public String url = " jdbc:mysql://localhost/"+db; public String user = "root"; public String pass = "1234"; //Constructor public ConexionMySQL(){ } //Mtodo para conexin public Connection Conectar(){ Connection link= null; try{ //cargamos el driver MySQL Class.forName("org.gjt.mm.mysql.Driver"); //Creamos enlace hacia la base de datos link = DriverManager.getConnection(this.url,this.user,this.pass); }catch(Exception e){ JOptionPane.showMessageDialog(null, e); } return link; }}

Hecho esto ahora vamos a comenzar a crear los formularios, para esto vamos a agregar un formulario jFrame en el paquete de Formularios.

Le escribimos el nombre de Clientes

Agregamos un panel y modificamos la propiedad border

Seleccionamos la opcin borde con ttulo y le escribimos Captura de Clientes

Ahora vamos agregar las etiquetas y las cajas de texto para darle diseo a la captura (Controles swing)

Ahora editamos el texto de cada objeto (La lista desplegable con la propiedad Model)

Ahora necesitamos cambiar las variables, aunque se debe cambiar a todos los objetos los ms importantes son las cajas de texto, la lista desplegable y botones.

La lista desplegable como: cboGenero

Los botones como: btnNuevo

Ahora vamos a cargar el combo (lista desplegable) con los valores masculino y femenino.Para hacer esto nos vamos al cdigo fuente

Vamos a buscar al constructor (que arranca cuando se inicializa el objeto o clase)

En esta parte agregamos dos elementos a la lista desplegablepublic Clientes() { initComponents(); cboGenero.addItem("Masculino"); cboGenero.addItem("Femenino"); }

Guardamos y ejecutamos

Vamos a programar el botn Salir (dando doble clic)

Quitamos el comentario y tecleamosprivate void btnSalirActionPerformed(java.awt.event.ActionEvent evt) { this.dispose(); }

Ahora vamos a crear los mtodos de habilitar y deshabilitar cajas de texto. Para esto vamos a crear nuevos mtodos, los vamos a poner debajo del mtodo constructor.//Mtodo de Deshabilitar void Deshabilitar(){ }

Con el vamos a deshabilitar los controles, para no poder escribir en l hasta que queramos crear un nuevo registro

//Mtodo de deshabilitar void Desabilitar(){ txtClave.setEnabled(false); txtNombre.setEnabled(false); txtDireccion.setEnabled(false); txtCredito.setEnabled(false); txtFecha.setEnabled(false); cboGenero.setEnabled(false); txtClave.setText(""); txtNombre.setText(""); txtDireccion.setText(""); txtTelefono.setText(""); txtFecha.setText(""); }

Vamos primeramente a programar que al arrancar el programa, todos los objetos estn deshabilitados, para esto vamos al constructor y mandamos llamar el mtodo.

public Clientes() { initComponents(); cboGenero.addItem("Masculino"); cboGenero.addItem("Femenino"); Deshabilitar(); }

Sera bueno tambin deshabilitar el botn de Cancelar y eliminar

btnGuardar.setEnabled(false);btnCancelar.setEnabled(false);

La idea es que cuando presionemos el botn de nuevo se habiliten las cajas y los dos botones y el de nuevo se deshabilite

Para esto vamos a crear el mtodo de habilitar (pasamos el control del cursos al primer campo)//Mtodo de habilitar void Habilitar(){ txtClave.setEnabled(true); txtNombre.setEnabled(true); txtDireccion.setEnabled(true); txtTelefono.setEnabled(true); txtFecha.setEnabled(true); cboGenero.setEnabled(true); btnGuardar.setEnabled(true); btnCancelar.setEnabled(true); txtClave.setText(""); txtNombre.setText(""); txtDireccion.setText(""); txtTelefono.setText(""); txtFecha.setText(""); txtClave.requestFocus(); }

Lo mandamos llamar en el botn de Nuevo

private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) { Habilitar(); }

Ejecutamos

Despus queremos que cuando se presione el botn de Cancelar, se deshabiliten las cajasprivate void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) { Deshabilitar(); }

Ahora lo que vamos a hacer es transferir el control de una caja de texto a otra mediante un enter. Para lograr esto necesitamos dar clic con el botn derecho a la caja de texto y despus seleccin la opcin: Eventos ---Action---ActionPerformed. (Lo hacemos en todas las cajas de texto).

Y en el mtodo que aparece tecleamos el siguiente cdigo:private void txtClaveActionPerformed(java.awt.event.ActionEvent evt) { txtClave.transferFocus(); }

El cdigo completo en esta parte debe quedar: private void txtClaveActionPerformed(java.awt.event.ActionEvent evt) { txtClave.transferFocus(); }

private void txtNombreActionPerformed(java.awt.event.ActionEvent evt) { txtNombre.transferFocus(); }

private void txtDireccionActionPerformed(java.awt.event.ActionEvent evt) { txtDireccion.transferFocus(); }

private void txtTelefonoActionPerformed(java.awt.event.ActionEvent evt) { txtTelefono.transferFocus(); }

private void txtFechaActionPerformed(java.awt.event.ActionEvent evt) { txtFecha.transferFocus(); }

Alta de Clientes

Ahora procedemos a generar el mtodo que nos permita introducir registros a la tabla. En este caso despus de capturar los datos, presionamos el botn de guardar y los datos se deben enviar a la base de datos.

Lo primero que tenemos que hacer es ir al botn guardar con el botn derecho y despus seleccin la opcin: Eventos ---Action---ActionPerformed.

Antes de comenzar a escribir el cdigo dentro del objeto guardar, arriba del mismo vamos a inicializar una variable tipo String que llamaremos accin y la inicializaremos como insertar.

String accion = "insertar";

Dentro de la programacin del objeto guardar, requerimos declarar una variable que llamaremos sql de tipo ConexionMySQL e inicializarla.

ConexionMySQL sql = new ConexionMySQL();

El programa va marcar un error, este indica que necesitamos especificar la librera que nos permita utilizar la clase ConexionMySQL, ya que se encuentra en otro paquete. Dejamos que Java lo solucione automticamente (presionando clic en el error)

Observa como la librera se agrega al inicio del cdigo.

import BaseDatos.ConexionMySQL;

Vamos a crear una variable que llamaremos cn y que ser de tipo conection y lo igualamos a la variable antes creada sql.Conectar();

Connection cn = sql.Conectar();

El cdigo:

String accion = "insertar"; private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) { ConexionMySQL sql = new ConexionMySQL(); Connection cn = sql.Conectar(); }

Marcar un error porque no tenemos la librera para la variable Connection, vamos a agregarla de manera la siguiente manera:

Import java.sql.*;

Hecho esto vamos a declarar una variables tipo String que nos van a permitir guardar ah los valores que escribamos en las cajas de texto.

String mClave,mNombre,mDireccion,mTelefono,mFecha,mGenero;

Ahora vamos a almacenar en cada una de las variables los valores capturados en las cajas de texto.

mClave=txtClave.getText(); mNombre=txtNombre.getText(); mDireccion=txtDireccion.getText(); mTelefono=txtTelefono.getText(); mFecha=txtFecha.getText();

Para guardar lo que contiene el comboBox, se requiere otro mtodo.

mGenero=cboGenero.getSelectedItem();

Solo que al ponerlo ocurre un error, esto es porque el tem es un objeto no es tipo String, por lo tanto tenemos que cambiar el tipo objeto a cadena de la siguiente forma:

mGenero=cboGenero.getSelectedItem().toString();

Ahora vamos a crear una variable tipo cadena en donde almacenaremos la sentencia de SQL que vamos a utilizar y la inicializamos en blanco.

String sSQL = "";

El cdigo hasta aqu es:

String accion = "insertar"; private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) { ConexionMySQL sql = new ConexionMySQL(); Connection cn = sql.Conectar(); String mClave, mNombre, mDireccion, mTelefono, mFecha, mGenero; String sSQL = ""; mClave=txtClave.getText(); mNombre=txtNombre.getText(); mDireccion=txtDireccion.getText(); mTelefono=txtTelefono.getText(); mFecha=txtFecha.getText(); mGenero=cboGenero.getSelectedItem().toString(); }

Ahora vamos a crear la sentencia de SQL como normalmente lo haramos

sSQL = "INSERT INTO Clientes(clave, nombre, direccion, credito, fecha, genero) + "VALUES(?,?,?,?,?,?)";

Vamos a crear una variable de tipo String donde almacenemos el texto del mensaje

String mensaje ="";

Despus de la sentencia SQL incorporamos el mensaje a la variable

mensaje = "Los datos se ingresaron de manera correcta...";

Ahora vamos crear el procedimiento para ingresar los valores de las variables a la base de datos, para esto utilizamos una interfaz que se llama PreparedStatement.

PreparedStatement pst = cn.prepareStatement(sSQL);

Nos marca un error, eso es porque Java pide una estructura try catch para poder ejecutar la lnea. Vamos agregarla automticamente.

try { PreparedStatement pst = cn.prepareStatement(sSQL);} catch (SQLException ex) { Logger.getLogger(Clientes.class.getName()).log(Level.SEVERE, null, ex); }

Cambiamos la lnea del logger por un mensaje de error

try { PreparedStatement pst = cn.prepareStatement(sSQL);} catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex); }

Una vez hecho esto vamos a ingresar cada uno de los datos en la cadena con el objeto pst y el mtodo setString()

Por ejemplo:

pst.setString(1, mClave);

lo anterior significa que en la primera interrogacin (de la estructura anterior) vamos a guardar lo que contenga la variable mClave. (y as sucesivamente)

pst.setString(1, mClave); pst.setString(2, mNombre); pst.setString(3, mDireccion); pst.setString(4, mCredito); pst.setString(5, mFecha); pst.setString(6, mGenero);

Lo nico que falta es ejecutar la consulta creada, para esto primero vamos a crear una variable entera donde se almacenen los registros que se ingresaron, si es 0 no se almacenaron registros, en caso de ser mayor a uno si se almacenaron registros. (Esto despus de lo anterior)

int n = pst.executeUpdate();

Ahora vamos a comprobar si los datos se insertaron.

if(n>0){ JOptionPane.showMessageDialog(null, mensaje); }

La estructura del try es:

try { PreparedStatement pst = cn.prepareStatement(sSQL); pst.setString(1, mClave); pst.setString(2, mNombre); pst.setString(3, mDireccion); pst.setString(4, mCredito); pst.setString(5, mFecha); pst.setString(6, mGenero); int n = pst.executeUpdate(); if(n>0){ JOptionPane.showMessageDialog(null, mensaje); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex); }

Y todo el cdigo hasta aqu:

package Formularios;

import BaseDatos.ConexionMySQL;import java.sql.*;import java.util.logging.Level;import java.util.logging.Logger;import javax.swing.JOptionPane;

/** * * @author Propietario */public class Clientes extends javax.swing.JFrame {

/** * Creates new form Clientes */ public Clientes() { initComponents(); cboGenero.addItem("Masculino"); cboGenero.addItem("Femenino"); Deshabilitar(); } /** * 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") // private void initComponents() {

jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); txtClave = new javax.swing.JTextField(); txtNombre = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); txtDireccion = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); txtCredito = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); txtFecha = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); cboGenero = new javax.swing.JComboBox(); btnNuevo = new javax.swing.JButton(); btnGuardar = new javax.swing.JButton(); btnCancelar = new javax.swing.JButton(); btnSalir = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Captura de Clientes"));

jLabel1.setText("Clave:");

txtClave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtClaveActionPerformed(evt); } });

txtNombre.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtNombreActionPerformed(evt); } });

jLabel2.setText("Nombre:");

txtDireccion.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtDireccionActionPerformed(evt); } });

jLabel3.setText("Direccin:");

txtCredito.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtCreditoActionPerformed(evt); } });

jLabel4.setText("Crdito");

txtFecha.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtFechaActionPerformed(evt); } });

jLabel5.setText("Fecha:");

jLabel6.setText("Gnero:");

btnNuevo.setText("Nuevo"); btnNuevo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNuevoActionPerformed(evt); } });

btnGuardar.setText("Guardar"); btnGuardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnGuardarActionPerformed(evt); } });

btnCancelar.setText("Cancelar"); btnCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelarActionPerformed(evt); } });

btnSalir.setText("Salir"); btnSalir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSalirActionPerformed(evt); } });

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(45, 45, 45) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtClave, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtCredito, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cboGenero, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(btnNuevo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnGuardar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnCancelar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnSalir))) .addContainerGap(64, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(txtClave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(txtCredito, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addComponent(cboGenero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnNuevo) .addComponent(btnGuardar) .addComponent(btnCancelar) .addComponent(btnSalir)) .addGap(0, 94, Short.MAX_VALUE)) );

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() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(14, Short.MAX_VALUE)) );

pack(); }//

//Mtodo de deshabilitar void Deshabilitar(){ txtClave.setEnabled(false); txtNombre.setEnabled(false); txtDireccion.setEnabled(false); txtCredito.setEnabled(false); txtFecha.setEnabled(false); cboGenero.setEnabled(false); btnGuardar.setEnabled(false); btnCancelar.setEnabled(false); txtClave.setText(""); txtNombre.setText(""); txtDireccion.setText(""); txtCredito.setText(""); txtFecha.setText(""); } //Mtodo de habilitar void Habilitar(){ txtClave.setEnabled(true); txtNombre.setEnabled(true); txtDireccion.setEnabled(true); txtCredito.setEnabled(true); txtFecha.setEnabled(true); cboGenero.setEnabled(true); btnGuardar.setEnabled(true); btnCancelar.setEnabled(true); txtClave.setText(""); txtNombre.setText(""); txtDireccion.setText(""); txtCredito.setText(""); txtFecha.setText(""); txtClave.requestFocus(); } private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) { this.dispose(); }

private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) { Habilitar(); }

private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) { Deshabilitar(); }

private void txtClaveActionPerformed(java.awt.event.ActionEvent evt) { txtClave.transferFocus(); }

private void txtNombreActionPerformed(java.awt.event.ActionEvent evt) { txtNombre.transferFocus(); }

private void txtDireccionActionPerformed(java.awt.event.ActionEvent evt) { txtDireccion.transferFocus(); }

private void txtCreditoActionPerformed(java.awt.event.ActionEvent evt) { txtCredito.transferFocus(); }

private void txtFechaActionPerformed(java.awt.event.ActionEvent evt) { txtFecha.transferFocus(); }

String accion = "insertar"; private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) { ConexionMySQL sql = new ConexionMySQL(); Connection cn = sql.Conectar(); String mClave, mNombre, mDireccion, mCredito, mFecha, mGenero; String sSQL = ""; String mensaje =""; mClave=txtClave.getText(); mNombre=txtNombre.getText(); mDireccion=txtDireccion.getText(); mCredito=txtCredito.getText(); mFecha=txtFecha.getText(); mGenero=cboGenero.getSelectedItem().toString(); sSQL = "INSERT INTO Clientes(clave, nombre, direccion, credito, fecha, genero)" + "VALUES(?,?,?,?,?,?)"; mensaje = "Los datos se ingresaron de manera correcta..."; try { PreparedStatement pst = cn.prepareStatement(sSQL); pst.setString(1, mClave); pst.setString(2, mNombre); pst.setString(3, mDireccion); pst.setString(4, mCredito); pst.setString(5, mFecha); pst.setString(6, mGenero); int n = pst.executeUpdate(); if(n>0){ JOptionPane.showMessageDialog(null, mensaje); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex); } }

/** * @param args the command line arguments */ public static void main(String args[]) { /* * Set the Nimbus look and feel */ // /* * 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(Clientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Clientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Clientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Clientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //

/* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() {

public void run() { new Clientes().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btnCancelar; private javax.swing.JButton btnGuardar; private javax.swing.JButton btnNuevo; private javax.swing.JButton btnSalir; private javax.swing.JComboBox cboGenero; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JTextField txtClave; private javax.swing.JTextField txtCredito; private javax.swing.JTextField txtDireccion; private javax.swing.JTextField txtFecha; private javax.swing.JTextField txtNombre; // End of variables declaration}

Ejecutamos el archivo y listo.

Botn para Eliminar BD.Ahora vamos a crear los botones y tablas para eliminar informacin.

Primero se va ser el botn en la pantalla, lo llamaremos eliminar siempre tomando en cuenta la conexin.

Ahora dentro del botn se va a capturar el siguiente cdigo, para que la operacin se de con xito.

private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) { ConexionMySQL sql = new ConexionMySQL(); Connection cn = sql.conectar();

String mEliminar; String sSQL= "";

String mensaje=""; mensaje="La Informacion se a Eliminado Correctamente...";

mEliminar=txtEliminar.getText(); sSQL="DELETE FROM Clientes where (clave=?)"; try { PreparedStatement pst = cn.prepareStatement(sSQL); pst.setString(1,mEliminar);int n = pst.executeUpdate();

if (n>0) JOptionPane.showMessageDialog (null,mensaje); else { JOptionPane.showMessageDialog (null,"No se Encuentra Dentro de la Base de Datos");

}

} catch (SQLException ex){

JOptionPane.showMessageDialog(null,ex);

JOptionPane.showMessageDialog (null,mensaje); }

// TODO add your handling code here: }

Ya terminado nos va a mostrar la siguiente pantalla:

Tambin se pude ver que nos manda un mensaje donde consta que la informacin en la base de datos fue eliminada correctamente.

Tambin se puede ver, si queremos volver a eliminar el mismo registro ya no nos deja, en caso de que ya no exista o haya sido eliminado el registro nos manda al mismo tiempo el mensaje, donde consta que los datos solicitados no estn en la base de datos, como lo vemos en la siguiente pantalla.

Botn Para Modificar Datos.Para modificar un registro de la base de datos solo insertamos otro botn llamado como tal, e insertamos nuestro cdigo all mismo en el botn.

El cdigo es el siguiente:

private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {

ConexionMySQL sql = new ConexionMySQL(); Connection cn = sql.conectar();

String mClave,mNombre,mDireccion,mCredito,mFecha,mGenero; mClave=txtClave.getText(); mNombre=txtNombre.getText(); mDireccion=txtDireccion.getText(); mCredito=txtCredito.getText(); mFecha=txtFecha.getText(); mGenero=cboGenero.getSelectedItem().toString();

String sSQL="";

sSQL= "UPDATE Clientes SET Nombre=?,Direccion=?,Credito=?,Fecha=?,Genero=? WHERE Clave=?";

String mensaje=""; mensaje="Los Datos Deseados Fueron Modificados";

try { PreparedStatement pst; pst=(PreparedStatement) cn.prepareStatement(sSQL); pst.setString(1, mNombre); pst.setString(2, mDireccion); pst.setString(3, mCredito); pst.setString(4, mFecha); pst.setString(5, mGenero); pst.setString(6, mClave);

int n = pst.executeUpdate();

if (n>0) JOptionPane.showMessageDialog (null,mensaje);

} catch (SQLException ex){ PreparedStatement pst; JOptionPane.showMessageDialog(null,ex);

// TODO add your handling code here: }

// TODO add your handling code here: }

Ya insertado:

Aqu ya se muestra la pantalla con el botn modificar, mencionando que el cdigo anterior debe de ir insertado en el botn anterior.

Al ejecutar nuestro programa y haciendo lo que el programa debe de hacer la podemos observar de esta manera.

Botn Para Buscar Para buscar insertaremos una tabla como Menu:Despus le ingresaremos el cdigo para atraer la base de datos.

/// Codigopublic class Clientes extends javax.swing.JFrame { /** * Creates new form Clientes */ void mostrardatos(String valor){ DefaultTableModel modelo= new DefaultTableModel(); ConexionMySQL sql = new ConexionMySQL(); Connection cn = sql.conectar(); modelo.addColumn("clave"); modelo.addColumn("Nombre"); modelo.addColumn("direccion"); modelo.addColumn("credito"); modelo.addColumn("fecha"); modelo.addColumn("genero"); tbClientes.setModel(modelo); String sSQL=""; if(valor.equals("")) { // sSQL="SELECT * FROM clientes"; } else{ sSQL="SELECT * FROM clientes WHERE clave='"+valor+"'"; } String []datos = new String [6]; try { PreparedStatement pst; pst=(PreparedStatement) cn.prepareStatement(sSQL); Statement st = cn.createStatement(); ResultSet rs = st.executeQuery(sSQL); while(rs.next()){ datos[0]=rs.getString(1); datos[1]=rs.getString(2); datos[2]=rs.getString(3); datos[3]=rs.getString(4); datos[4]=rs.getString(5); datos[5]=rs.getString(6); modelo.addRow(datos); } tbClientes.setModel(modelo); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex); } }

Por ltimo la pantalla quedara en si as;

Pgina 34