Práctica dirigida

10
PROGRAMACIÓN TRES CAPAS CREACIÓN DE UNA APLICACIÓN EN NETBEANS CON CONEXIÓN A ORACLE 10G A. CREAR UNA APLICACIÓN EN JAVA CON EL NOMBRE appConexionOracle. B. Agregue un paquete para la capa lógica con el nombre logic. C. Agregue dentro del paquete logic una clase con el nombre clsConexion. Copie el siguiente código en la clsConexion. SERÁ EXPLICADO DETALLADAMENTE. package logic; import java.sql.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.table.DefaultTableModel; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Ing. Gloriana Peña Ramírez */ public class clsConexion { //ATRIBUTOS DE LA CLASE CLSCONEXION protected Connection conexion;//Para hacer la conexión protected CallableStatement obj_Procedimiento;//Utilizar los procedure protected Statement stmt;//Hacer sentencias SQL protected ResultSet rs;//Guardar los resultados de las sentencias SQL //MÉTODOS PÚBLICOS DE LA CLASE CONEXCIONBD //Constructor default public clsConexion() { conexion=null; obj_Procedimiento=null; }//========================================================================= //Establece conexion a Oracle con el usuario y clave establecidos public void conectarBD() { try {//Se debe agregar la librería odbcd14.jar para poder correrlo Class.forName("oracle.jdbc.driver.OracleDriver"); conexion = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "estudiante","123"); System.out.println("Conexion exitosa"); } catch (SQLException ex) {

description

Conexión a base de datos Oracle, gestión (guardar, buscar, editar, eliminar otros) de una tabla

Transcript of Práctica dirigida

Page 1: Práctica dirigida

PROGRAMACIÓN TRES CAPAS

CREACIÓN DE UNA APLICACIÓN EN NETBEANS CON CONEXIÓN A ORACLE 10G

A. CREAR UNA APLICACIÓN EN JAVA CON EL NOMBRE appConexionOracle.

B. Agregue un paquete para la capa lógica con el nombre logic.

C. Agregue dentro del paquete logic una clase con el nombre clsConexion.

Copie el siguiente código en la clsConexion. SERÁ EXPLICADO DETALLADAMENTE.

package logic; import java.sql.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.table.DefaultTableModel; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Ing. Gloriana Peña Ramírez */ public class clsConexion { //ATRIBUTOS DE LA CLASE CLSCONEXION protected Connection conexion;//Para hacer la conexión protected CallableStatement obj_Procedimiento;//Utilizar los procedure protected Statement stmt;//Hacer sentencias SQL protected ResultSet rs;//Guardar los resultados de las sentencias SQL //MÉTODOS PÚBLICOS DE LA CLASE CONEXCIONBD //Constructor default public clsConexion() { conexion=null; obj_Procedimiento=null; }//========================================================================= //Establece conexion a Oracle con el usuario y clave establecidos public void conectarBD() { try {//Se debe agregar la librería odbcd14.jar para poder correrlo Class.forName("oracle.jdbc.driver.OracleDriver"); conexion = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "estudiante","123"); System.out.println("Conexion exitosa"); } catch (SQLException ex) {

Page 2: Práctica dirigida

System.out.println(ex.getMessage()); } catch (ClassNotFoundException ex) { System.out.println(ex.getMessage()); } }//========================================================================= //Desconecta la conexion con Oracle y el usuario establecidos anteriormente public void desconectarBD() { try { if(conexion != null){ conexion.close(); System.out.println("Desconexion Exitosa"); } } catch (SQLException ex) { System.out.println("Error al desconectar " + ex.getMessage()); Logger.getLogger(clsConexion.class.getName()).log(Level.SEVERE, null, ex); } }//========================================================================= //MÉTODO ESPECIAL QUE PERMITE IMPRIMIR LOS RESULTADOS ESTABLECIDOS EN LAS //CONSULTAS SQL EN LOS JTABLES DE LOS FORMULARIOS, EN FORMA GENERAL PARA //CUALQUIER JTABLE Y CUALQUIER CONSULTA public DefaultTableModel cargarEnTabla(ResultSet rs) { DefaultTableModel modelo = new DefaultTableModel(); ResultSetMetaData metaDatos; Object[] etiquetas; int numeroColumnas; try { metaDatos = rs.getMetaData(); numeroColumnas = metaDatos.getColumnCount(); etiquetas = new Object[numeroColumnas]; // Se obtiene cada una de las etiquetas para cada columna for (int i = 0; i < numeroColumnas; i++) { // Nuevamente, para ResultSetMetaData la primera columna es la 1. etiquetas[i] = metaDatos.getColumnLabel(i + 1); } modelo.setColumnIdentifiers(etiquetas); while (rs.next()) { // Se crea un array que será una de las filas de la tabla. Object[] fila = new Object[numeroColumnas]; // Hay tres columnas en la tabla // Se rellena cada posición del array con una de las columnas de la tabla en base de datos. for (int i = 0; i < numeroColumnas; i++) { fila[i] = rs.getObject(i + 1); // El primer indice en rs es el 1, no el cero, por eso se suma 1. } // Se añade al modelo la fila completa. modelo.addRow(fila); } } catch (SQLException ex) { Logger.getLogger(clsConexion.class.getName()).log(Level.SEVERE, null, ex); } return modelo; }//========================================================================= //Método que ejecuta cualquier consulta select pasada por parametro public ResultSet ejecutarSQLSelect(String sql) { try { stmt = conexion.createStatement(); rs = stmt.executeQuery(sql); } catch (SQLException ex) { System.out.println(ex.getMessage()); } return rs; }//=========================================================================

Page 3: Práctica dirigida

//Método que ejecuta cualquier sentencia de actualización(update, delete, //insert) pasada por parametro. public void ejecutarSQL(String sql) { try { stmt = conexion.createStatement(); stmt.executeUpdate(sql); } catch (SQLException ex) { System.out.println(ex.getMessage()); } }//========================================================================= }

D. INCLUYA EN LA CARPETA LIBRARIES EL DRIVER DE ORACLE.

Pasos:

1. Clic derecho en la carpeta libraries

2. Elija la opción Add JAR/Folder…

3. Busque la ruta y el driver de Oracle archivo sqljdbc4,

suministrado por la profesora en la carpeta semana 02.

E. PRUEBA LA CONEXIÓN EN EL MAIN DEL ARCHIVO appConexionOracle.java

Page 4: Práctica dirigida

F. AGREGUE DENTRO DEL PAQUETE LOGIC UNA CLASE CON EL NOMBRE clsPersona.java

package logic; public class clsPersona { //Atributos de la clase private int id; private String nombre; private String apellidos; private int edad; //Constructor default public clsPersona() { this.id = 0; this.nombre = ""; this.apellidos = ""; this.edad = 0; } //Constructor parámetros public clsPersona(int id, String nombre, String apellidos, int edad) { this.id = id; this.nombre = nombre; this.apellidos = apellidos; this.edad = edad; } //Getter and Setter public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellidos() { return apellidos; } public void setApellidos(String apellidos) { this.apellidos = apellidos; } public int getEdad() { return edad; } public void setEdad(int edad) { this.edad = edad; } }

Page 5: Práctica dirigida

G. AGREGUE DENTRO DEL PAQUETE LOGIC UNA CLASE CON EL NOMBRE clsGestorPersona.java

H. INCLUYA EL SIGUIENTE CÓDIGO FUENTE SERÁ EXPLICADO DETALLADAMENTE

package logic; import java.sql.ResultSet; import java.sql.SQLException; /** * * @author Gloriana */ public class clsGestorPersona extends clsConexion{ //SIN ATRIBUTOS HEREDADOS DE CLSCONEXION //MÉTODOS public ResultSet buscarTodasPersonas() { String sql = "SELECT id,nombre,apellidos,edad " + "FROM tblPersona"; try { stmt = conexion.createStatement(); rs = stmt.executeQuery(sql); } catch (SQLException ex) { System.out.println(ex.getMessage()); } return rs; }//========================================================================= public ResultSet buscarPersona(int idPersona) { String sql = "SELECT id,nombre,apellidos,edad " + "FROM tblPersona " + "WHERE id= " + idPersona; try { stmt = conexion.createStatement(); rs = stmt.executeQuery(sql); } catch (SQLException ex) { System.out.println(ex.getMessage()); } return rs; }//========================================================================= public void insertarPersona(clsPersona persona) { try { //Llamar al procedimiento obj_Procedimiento = conexion.prepareCall("{call insertarPersona(?,?,?,?)}"); //Definir la Entradas o parametros (?) del Procedimiento Almacenado obj_Procedimiento.setInt(1, persona.getId()); obj_Procedimiento.setString(2, persona.getNombre()); obj_Procedimiento.setString(3, persona.getApellidos()); obj_Procedimiento.setInt(4, persona.getEdad()); obj_Procedimiento.execute(); } catch (SQLException ex) { System.out.println(ex.getMessage()); } }//========================================================================= public void editarPersona(clsPersona persona) { try { //Llamar al procedimiento obj_Procedimiento = conexion.prepareCall("{call editarPersona(?,?,?,?)}"); //Definir la Entradas o parametros (?) del Procedimiento Almacenado obj_Procedimiento.setInt(1, persona.getId()); obj_Procedimiento.setString(2, persona.getNombre()); obj_Procedimiento.setString(3, persona.getApellidos()); obj_Procedimiento.setInt(4, persona.getEdad()); obj_Procedimiento.execute();

Page 6: Práctica dirigida

} catch (SQLException ex) { System.out.println(ex.getMessage()); } }//========================================================================= public void eliminarPersona(int idPersona) { try { //Llamar al procedimiento obj_Procedimiento = conexion.prepareCall("{call eliminarPersona(?)}"); //Definir la Entradas o parametros (?) del Procedimiento Almacenado obj_Procedimiento.setInt(1, idPersona); //Ejecutamos el Procedimiento obj_Procedimiento.execute(); } catch (SQLException ex) { System.out.println(ex.getMessage()); } }//========================================================================= }

I. CREACIÓN DEL FORMULARIO PARA GESTIONAR LA BD EN ORACLE.

J. AGREGUE LA CARPETA IMG SUMINSTRADA POR LA PROFESORA QUE CONTIENE LAS IMÁGENES PARA LA

TOOL BAR DEL PROYECTO.

K. CREE UN PAQUETE CON EL NOMBRE GUI (INTERFAZ GRÁFICA DE USUARIO –CAPA DE PRESENTACIÓN–)

L. Agregue un formulario con el nombre frmPersona dentro del paquete gui.

M. DISEÑE EL FORMULARIO SIMILAR A LA SIGUIENTE FIGURA

Page 7: Práctica dirigida

N. DECLARE LAS SIGUIENTES VARIABLES GLOBALES

O. AGREGUE LOS SIGUIENTES MÉTODOS AL ARCHIVO FRMPERSONA. SERÁN EXPLICADOS DETALLADAMENTE

private void cargarDatos() { gestorPersona.conectarBD(); rs = gestorPersona.buscarTodasPersonas(); tabla.setModel(gestorPersona.cargarEnTabla(rs)); gestorPersona.desconectarBD(); }//=========================================================================

private String validarDatos() { String mensaje = ""; if (txtId.getText().equals("")) { mensaje += "Por favor digite el id de la persona \n"; } else if (!IsNumero(txtId.getText())) { mensaje += "Por favor digite el id de la persona solo con numeros\n"; } if (txtNombre.getText().equals("")) { mensaje += "Por favor digite el nombre \n"; } if (txtApellidos.getText().equals("")) { mensaje += "Por favor digite los apellidos \n"; } if (txtEdad.getText().equals("")) { mensaje += "Por favor digite la edad \n"; } else if (!IsNumero(txtEdad.getText())) { mensaje += "Por favor digite la edad solo con numeros\n"; } return mensaje; }//=========================================================================

boolean IsNumero(String dato) { try { int num = Integer.parseInt(dato); return true; } catch (NumberFormatException ex) { return false; } }//=========================================================================

Page 8: Práctica dirigida

private void limpiarCampos() {

txtId.setText("");

txtNombre.setText("");

txtApellidos.setText("");

txtEdad.setText("");

}

P. AGREGUE EL SIGUIENTE CÓDIGO A CADA UNO DE LOS BOTONES DE LA TOOLBARR.

private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) { int idPersona; if (txtId.getText().equals("")) { idPersona = Integer.parseInt(JOptionPane.showInputDialog("Ingrese el id Persona a buscar")); } else { idPersona = Integer.parseInt(txtId.getText()); } gestorPersona.conectarBD(); rs = gestorPersona.buscarPersona(idPersona); try { if (rs.next()) { //Si lo encontr txtId.setText("" + rs.getInt("id")); txtNombre.setText(rs.getString("nombre")); txtApellidos.setText(rs.getString("apellidos")); txtEdad.setText("" + rs.getInt("edad")); } else { JOptionPane.showMessageDialog(rootPane, "Id "+ idPersona +" no encontrado."); limpiarCampos(); } } catch (SQLException ex) { System.out.println(ex.getMessage()); } gestorPersona.desconectarBD(); }

private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) { if (validarDatos().equals("")) { persona = new clsPersona(); persona.setId(Integer.parseInt(txtId.getText())); persona.setNombre(txtNombre.getText()); persona.setApellidos(txtApellidos.getText()); persona.setEdad(Integer.parseInt(txtEdad.getText())); gestorPersona.conectarBD(); rs = gestorPersona.buscarPersona(Integer.parseInt(txtId.getText())); try { if (!rs.next()) { gestorPersona.insertarPersona(persona); JOptionPane.showMessageDialog(rootPane, persona.getNombre()+" almacenado."); } else { JOptionPane.showMessageDialog(rootPane, "Id. de persona ya ingresado"); } } catch (SQLException ex) { System.out.println(ex.getMessage()); } cargarDatos(); gestorPersona.desconectarBD(); } else { JOptionPane.showMessageDialog(rootPane, validarDatos()); }

Page 9: Práctica dirigida

}

private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) { if (validarDatos().equals("")) { persona = new clsPersona(); persona.setId(Integer.parseInt(txtId.getText())); persona.setNombre(txtNombre.getText()); persona.setApellidos(txtApellidos.getText()); persona.setEdad(Integer.parseInt(txtEdad.getText())); gestorPersona.conectarBD(); rs = gestorPersona.buscarPersona(Integer.parseInt(txtId.getText())); try { if (rs.next()) { gestorPersona.editarPersona(persona); JOptionPane.showMessageDialog(rootPane, persona.getId()+" editado."); } else { JOptionPane.showMessageDialog(rootPane, "Id. de persona no encontrado para editar"); } } catch (SQLException ex) { System.out.println(ex.getMessage()); } cargarDatos(); gestorPersona.desconectarBD(); } else { JOptionPane.showMessageDialog(rootPane, validarDatos()); } }

private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) { int idPersona; if (txtId.getText().equals("")) { idPersona = Integer.parseInt(JOptionPane.showInputDialog("Ingrese el id Persona a buscar")); } else { idPersona = Integer.parseInt(txtId.getText()); } gestorPersona.conectarBD(); rs = gestorPersona.buscarPersona(idPersona); try { if (rs.next()) { gestorPersona.eliminarPersona(idPersona); cargarDatos(); JOptionPane.showMessageDialog(rootPane, "Persona eliminado"); } else { JOptionPane.showMessageDialog(rootPane, "Id de persona no encontrado"); } } catch (SQLException ex) { System.out.println(ex.getMessage()); } gestorPersona.desconectarBD(); }

private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) { try { //Mensaje de encabezado MessageFormat headerFormat = new MessageFormat("Listado de personas"); //Mensaje en el pie de pagina MessageFormat footerFormat = new MessageFormat("ContreSpace"); //Imprimir JTable tabla.print(JTable.PrintMode.NORMAL, headerFormat, footerFormat); } catch (PrinterException ex) { System.out.println(ex.getMessage()); } }

Page 10: Práctica dirigida

private void btnLimpiarActionPerformed(java.awt.event.ActionEvent evt) { limpiarCampos(); }

private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) { int resp = JOptionPane.showConfirmDialog(rootPane, "¿Está seguro de salir?", "Salir",JOptionPane.YES_NO_OPTION); if(resp == JOptionPane.YES_OPTION){ System.exit(1); } }

NOTA:

Recuerde incluir en el método WindowsOpened del formulario la llamada al método cargarDatos();, parque que al

abrirse el formulario cargue los datos en el JTable.

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

Agregue al proyecto appConexionOracle

o Una clase llamada clsProducto, y una clase clsGestorProducto que gestione la tabla producto de la

primera tarea corta asignada por la profesora.

o Agregue un formulario frmProducto que gestione los datos de la tabla productos. Guíese con el

proyecto realizado anteriormente.