5
CODIGOS DE ALTAS-BAJAS-MODIFICACIONES (BÁSICO JAVA) package proyectoeventos; public class frmCursoTaller extends javax.swing.JFrame { DefaultTableModel mitabla = new DefaultTableModel(); conexion cn; private static char opcion; /** Creates new form frmCursoTaller */ public frmCursoTaller() { initComponents(); cn = new conexion(); // definicion de la tabla mitabla.addColumn("Id Curso"); mitabla.addColumn("Descripción"); mitabla.addColumn("Fecha"); mitabla.addColumn("Costo"); mitabla.addColumn("Observación"); modoEdicion(false); mostrarDatos(); } private void bModificarActionPerformed(java.awt.event.ActionEvent evt) { int fMod = listaCursos.getSelectedRow(); //asigna fila seleccionada if (fMod==-1) { JOptionPane.showMessageDialog(null, "No se ha seleccionado ningún registro","Error",JOptionPane.ERROR_MESSAGE); } else { modoEdicion(true); txtDescripcion.grabFocus(); opcion = 'M'; } } private void bCancelarActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: modoEdicion(false); limpiarCuadros(); mostrarDatos(); } private void bGuardarActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: switch(opcion){ case 'N': accionInsertar(); break; case 'M': accionActualizar(); break; } this.limpiarCuadros(); this.modoEdicion(false); mostrarDatos(); } 1

ABM Basico

Embed Size (px)

Citation preview

Page 1: ABM Basico

CODIGOS DE ALTAS-BAJAS-MODIFICACIONES (BÁSICO JAVA)

package proyectoeventos;

public class frmCursoTaller extends javax.swing.JFrame { DefaultTableModel mitabla = new DefaultTableModel(); conexion cn; private static char opcion;

/** Creates new form frmCursoTaller */ public frmCursoTaller() { initComponents(); cn = new conexion(); // definicion de la tabla mitabla.addColumn("Id Curso"); mitabla.addColumn("Descripción"); mitabla.addColumn("Fecha"); mitabla.addColumn("Costo"); mitabla.addColumn("Observación"); modoEdicion(false); mostrarDatos(); }

private void bModificarActionPerformed(java.awt.event.ActionEvent evt) { int fMod = listaCursos.getSelectedRow(); //asigna fila seleccionada if (fMod==-1) { JOptionPane.showMessageDialog(null, "No se ha seleccionado ningún registro","Error",JOptionPane.ERROR_MESSAGE); } else { modoEdicion(true); txtDescripcion.grabFocus(); opcion = 'M'; } }

private void bCancelarActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: modoEdicion(false); limpiarCuadros(); mostrarDatos(); }

private void bGuardarActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: switch(opcion){ case 'N': accionInsertar(); break; case 'M': accionActualizar(); break; } this.limpiarCuadros(); this.modoEdicion(false); mostrarDatos(); }

1

Page 2: ABM Basico

private void bAgregarActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: ResultSet rs = null; try {// Creacion de la consulta java.sql.Statement sentencia = cn.getConexion().createStatement();// Ejecucion de la consulta rs = (ResultSet) sentencia.executeQuery("SELECT MAX(idCURSO_TALLER) FROM CURSOTALLER"); // desplazar al primer registro rs.first(); limpiarCuadros();// asignar cuadro de texto el codigo ultimo mas 1 txtIdCurso.setText(String.valueOf(rs.getInt(1)+1)); modoEdicion(true); txtDescripcion.grabFocus(); opcion = 'N'; } catch (SQLException e) {// Si ocurrio un error se muestra el mensaje JOptionPane.showMessageDialog(null, "Error codigo." , "Codigo", JOptionPane.ERROR_MESSAGE); } }

private void cargarCuadros() { // TODO add your handling code here: int fMod; try { fMod = listaCursos.getSelectedRow(); //asigna fila seleccionada if (fMod==-1) { JOptionPane.showMessageDialog(null, "No se ha seleccionado ningún registro"); } else {

mitabla = (DefaultTableModel) listaCursos.getModel();

String xi = (String) mitabla.getValueAt(fMod, 0).toString(); String xd = (String) mitabla.getValueAt(fMod, 1); String xf = (String) mitabla.getValueAt(fMod, 2).toString(); String xc = (String) mitabla.getValueAt(fMod, 3).toString(); String xo = (String) mitabla.getValueAt(fMod, 4);

this.txtIdCurso.setText(xi); this.txtDescripcion.setText(xd); this.txtFecha.setText(xf); this.txtCosto.setText(xc); this.txtObs.setText(xo);

} } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al extraer el registro","Resultado",JOptionPane.ERROR_MESSAGE); } }

2

Page 3: ABM Basico

private void bEliminarActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: int fEli; try { fEli = listaCursos.getSelectedRow(); //asigna fila seleccionada if (fEli==-1) { JOptionPane.showMessageDialog(null, "No se ha seleccionado ningún registro","Error",JOptionPane.ERROR_MESSAGE); } else { String xds = txtDescripcion.getText(); int resp = JOptionPane.showConfirmDialog(null, "Esta seguro que desea eliminar el registro "+ "\n =>"+xds.toUpperCase()+"<= del Sistema?", "Confirme la eliminación", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); // Si la respuestra es si if (resp == JOptionPane.YES_OPTION){ String xid = this.txtIdCurso.getText(); String consulta = "DELETE FROM CURSOTALLER WHERE idCURSO_TALLER ='"+ xid +"'";

java.sql.Statement sentencia = cn.getConexion().createStatement(); sentencia.executeUpdate(consulta); } mostrarDatos(); limpiarCuadros(); } } catch (SQLException e) { // Si ocurrio un error se muestra el mensaje if (e.getErrorCode()==1451){ JOptionPane.showMessageDialog(null, "Esta relacionado con otros registros no podra eliminarlo!", "Eliminar", JOptionPane.INFORMATION_MESSAGE); }else{ JOptionPane.showMessageDialog(null, "Error eliminar registro.", "Eliminar registro", JOptionPane.ERROR_MESSAGE); } return; } }

private void limpiarCuadros() { this.txtIdCurso.setText(""); this.txtDescripcion.setText(""); this.txtFecha.setText(""); this.txtCosto.setText(""); this.txtObs.setText(""); }

3

Page 4: ABM Basico

private void accionInsertar() { try { // insertar el registro indicando nombre_tabla, nombres_campos y valores_cuadro_de_textos // Asignación de valores de cuadros a variables locales del evento String c1 = this.txtIdCurso.getText(); String c2 = this.txtDescripcion.getText(); String c3 = this.txtFecha.getText(); String c4 = this.txtCosto.getText(); String c5 = this.txtObs.getText(); // Creacion de la actualizacion java.sql.Statement sentencia = cn.getConexion().createStatement(); // Se ejecuta la actualizacion String consulta="INSERT INTO CURSOTALLER VALUES ('"+c1+"','"+c2+"','"+c3+"','"+c4+"','"+c5+"')"; sentencia.executeUpdate(consulta); }catch (SQLException e){ if (e.getErrorCode()==1062){ JOptionPane.showMessageDialog(null, "No se pudo insertar un registro, ya existe uno similar", "Inserción", JOptionPane.ERROR_MESSAGE); }} }

private void accionActualizar() { try { // modidicar el registro indicando nombre_tabla, nombres_campos, valores_cuadro_de_textos y condicion // Asignación de valores de cuadros a variables locales del evento String c1 = this.txtIdCurso.getText(); String c2 = this.txtDescripcion.getText(); String c3 = this.txtFecha.getText(); String c4 = this.txtCosto.getText(); String c5 = this.txtObs.getText(); String consulta = "UPDATE CURSOTALLER SET CUR_DESCRI ='"+ c2 +"', CUR_FECHA ='"+ c3 +"', CUR_COSTO ='"+ c4 +"', CUR_OBS = '"+ c5 +"' WHERE idCURSO_TALLER ='"+ c1 +"'"; java.sql.Statement sentencia = cn.getConexion().createStatement(); sentencia.executeUpdate(consulta); } catch (Exception e) {}; } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new frmCursoTaller().setVisible(true); } }); }

4

Page 5: ABM Basico

private void mostrarDatos() { ResultSet rsP = null; mitabla.setRowCount(0); //Elimina los registros

try{ java.sql.Statement sentencia = cn.getConexion().createStatement();// Ejecucion de la consulta// String xSql = "SELECT * FROM PARTICIPANTE"; rsP = sentencia.executeQuery("SELECT * FROM CURSOTALLER");

while (rsP.next()) { Object[] datos = new Object[5]; for (int i=0;i<5;i++) { datos[i] = rsP.getObject(i+1); } mitabla.addRow(datos); } listaCursos.setModel(mitabla);

} catch(Exception e){// Si ocurrio un error se muestra el mensaje JOptionPane.showMessageDialog(null, "Error consulta." , "Consulta", JOptionPane.ERROR_MESSAGE); } }

private void modoEdicion(boolean vL){ this.bAgregar.setEnabled(!vL); this.bGuardar.setEnabled(vL); this.bCancelar.setEnabled(vL); this.bModificar.setEnabled(!vL); this.bEliminar.setEnabled(!vL); this.bCerrar.setEnabled(!vL);

//this.txtIdCurso.setEnabled(vL); this.txtDescripcion.setEnabled(vL); this.txtFecha.setEnabled(vL); this.txtCosto.setEnabled(vL); this.txtObs.setEnabled(vL);

this.listaCursos.setEnabled(!vL); }}

5