Advertisement
Guest User

Untitled

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