Advertisement
Guest User

Menu y Submenu

a guest
Jan 22nd, 2020
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.74 KB | None | 0 0
  1. import java.sql.*;
  2. import static java.lang.System.exit;
  3. import java.util.Scanner;
  4. import java.util.logging.Level;
  5. import java.util.logging.Logger;
  6.  
  7. public class Main {
  8.  
  9.     public static void main(String[] args) /*throws SQLException*/ {
  10.         try {
  11.             Class.forName("com.mysql.jdbc.Driver");
  12.         } catch (ClassNotFoundException ex) {
  13.             System.out.println("Librearía no cargada");
  14.             exit(1);
  15.         }
  16.         Connection con = null;
  17.         Statement sentencia = null;
  18.         ResultSet rs = null;
  19.         int n = 0;
  20.         //Comienza programa para fomar la sentencia
  21.         while (n != 99) {
  22.             System.out.println("1. Insertar");
  23.             System.out.println("2. Consultar");
  24.             System.out.println("");
  25.             System.out.println("99. SALIR DEL PROGRAMA");
  26.             System.out.println("");
  27.             System.out.print("   Selecciona opción: ");
  28.  
  29.             n = (new Scanner(System.in).nextInt());
  30.             switch (n) {
  31.                 case 1:
  32.                     while (n != 3) {
  33.                         System.out.println("");
  34.                         System.out.println("1. Insertar Empleado");
  35.                         System.out.println("2. Insertar Oficina");
  36.                         System.out.println("3. ATRÁS");
  37.                         System.out.println("");
  38.                         System.out.print("   Selecciona opción: ");
  39.                         System.out.println("");
  40.                         n = (new Scanner(System.in).nextInt());
  41.                         switch (n) {
  42.                             case 1:
  43.                                 System.out.print("Introduzca número de empleado a insertar: ");
  44.                                 int numemp = (new Scanner(System.in).nextInt());
  45.                                 if (existeEmpleado(numemp)) {
  46.                                     System.out.println("El empleado ya existe en la BD");
  47.                                     System.out.println("");
  48.                                 } else {
  49.                                     System.out.print("Introduzca nombre: ");
  50.                                     String nombre = (new Scanner(System.in).nextLine());
  51.                                     System.out.print("Introduzca edad: ");
  52.                                     int edad = (new Scanner(System.in).nextInt());
  53.                                     System.out.print("Introduzca la oficina: ");
  54.                                     int oficina = (new Scanner(System.in).nextInt());
  55.                                     String sql = "INSERT INTO empleados (numemp, nombre, edad, oficina) VALUES (" + numemp + ", '" + nombre + "', " + edad + ", " + oficina + ");";
  56.                                     System.out.println(sql);
  57.                                     con = conecta();
  58.                                     ejecutaUpdate(con, sql);
  59.                                     System.out.println("HECHO. Empleado insertado.");
  60.                                 }
  61.                                 break;
  62.  
  63.                             case 2:
  64.                                 System.out.print("Introduzca número de oficina a insertar: ");
  65.                                 int oficina = (new Scanner(System.in).nextInt());
  66.                                 if (existeOficina(oficina)) {
  67.                                     System.out.println("La oficina ya existe en la BD");
  68.                                     System.out.println("");
  69.                                 } else {
  70.                                     System.out.print("Introduzca ciudad: ");
  71.                                     String ciudad = (new Scanner(System.in).nextLine());
  72.                                     System.out.print("Introduzca región: ");
  73.                                     String region = (new Scanner(System.in).nextLine());
  74.                                    
  75.                                     String sql = "INSERT INTO oficinas (oficina, ciudad, region) VALUES (" + oficina + ", '" + ciudad + "', '" + region + "');";
  76.                                     System.out.println(sql);
  77.                                     con = conecta();
  78.                                     ejecutaUpdate(con, sql);
  79.                                     System.out.println("HECHO. Oficina insertada.");
  80.                                 }
  81.                                 break;
  82.                             case 3:
  83.                                 break;
  84.                         }
  85.                     }
  86.  
  87.                 case 2:
  88.                     System.out.println("");
  89.                         System.out.println("1. Consultar Empleado");
  90.                         System.out.println("2. Consultar Oficina");
  91.                         System.out.println("3. ATRÁS");
  92.                         System.out.println("");
  93.                         System.out.print("   Selecciona opción: ");
  94.                         n = (new Scanner(System.in).nextInt());
  95.             }
  96.         }
  97.         System.out.println("FIN DEL PROGRAMA");
  98.     }
  99.  
  100.     /* Abre una conexión con la BD y devuelve el objeto */
  101.     private static Connection conecta() {
  102.         Connection con = null; //objeto con la conexión
  103.  
  104.         try {
  105.             // Realizamos la conexión
  106.             con = DriverManager.getConnection("jdbc:mysql://localhost/Empresa", "root", "Per12345"); //modificar usuario/contraseña segúnnuestra BD
  107.             // Ok: avisamos
  108.             System.out.println("Conectados...");
  109.  
  110.         } catch (Exception e) {
  111.             System.out.println("Error de conexión");
  112.         }
  113.  
  114.         return con;
  115.     }
  116.  
  117.     /* En la conexión pasada ejecuta la sentencia sql (que debe ser un SELECT)
  118.  * Devuelve el resultado de la consulta como un ResultSet */
  119.     static ResultSet ejecuta(Connection con, String sql) {
  120.         ResultSet rs = null;
  121.  
  122.         Statement sentencia;
  123.         try {
  124.             sentencia = con.createStatement();
  125.             rs = sentencia.executeQuery(sql);
  126.  
  127.         } catch (SQLException ex) {
  128.             System.out.println("Error SQL");
  129.         }
  130.  
  131.         return rs;
  132.     }
  133.  
  134.     /* En la conexión pasada ejecuta la sentencia sql (que debe ser un UPDATE, INSERT o DELETE)
  135.  * En este caso no se devuelve nada. */
  136.     static void ejecutaUpdate(Connection con, String sql) {
  137.         Statement sentencia;
  138.  
  139.         try {
  140.             sentencia = con.createStatement();
  141.             sentencia.executeUpdate(sql);
  142.  
  143.         } catch (SQLException ex) {
  144.             System.out.println("Error SQL");
  145.         }
  146.     }
  147.  
  148.     /* Comprueba si en la BD existe el empleado con el numemp pasado como parámetro */
  149.     static boolean existeEmpleado(int numemp) {
  150.         boolean existe = false;
  151.         try {
  152.             Connection con = conecta();
  153.             ResultSet rs = ejecuta(con, "SELECT * FROM Empleados WHERE numemp = " + numemp + ";");
  154.  
  155.             if (rs.next()) {
  156.                 existe = true;
  157.             }
  158.             con.close();
  159.  
  160.         } catch (SQLException ex) {
  161.             System.out.println("Error de ResultSet");
  162.         }
  163.         return existe;
  164.     }
  165.  
  166.     /* Comprueba si en la BD existe la oficina con el número de oficina pasado como parámetro */
  167.     static boolean existeOficina(int oficina) {
  168.         boolean existe = false;
  169.         try {
  170.             Connection con = conecta();
  171.             ResultSet rs = ejecuta(con, "SELECT * FROM Oficinas WHERE oficina = " + oficina + ";");
  172.  
  173.             if (rs.next()) {
  174.                 existe = true;
  175.             }
  176.             con.close();
  177.  
  178.         } catch (SQLException ex) {
  179.             System.out.println("Error ResultSet");
  180.         }
  181.         return existe;
  182.     }
  183.  
  184. // Función de ejemplo que muestra las oficinas que pertenecen a una región (norte, sur, ...)
  185.     private static void oficinasRegion() {
  186.  
  187.         //pedimos los datos
  188.         System.out.println("Region?");
  189.         String region = new Scanner(System.in).nextLine();
  190.  
  191.         //creamos la sentencia sql que nos interesa
  192.         String sql = "SELECT * FROM Oficinas "
  193.                 + "Where region='" + region + "';";
  194.  
  195.         Connection con = conecta(); //creamos la conexión
  196.         ResultSet rs = ejecuta(con, sql); //ejecutamos
  197.         try {
  198.             //recorremos el ResultSet y mostramos los datos
  199.             while (rs.next()) {
  200.                 String res = rs.getString("oficina") + ", "
  201.                         + rs.getString("ciudad") + ", "
  202.                         + rs.getString("region") + ", "
  203.                         + rs.getString("dir") + ", "
  204.                         + rs.getString("ventas");
  205.                 System.out.println(res);
  206.             }
  207.             //cerramos la conexión
  208.             con.close();
  209.         } catch (SQLException ex) {
  210.             System.out.println("Error de SQL");
  211.         }
  212.  
  213.     }
  214.  
  215. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement