Advertisement
Guest User

Untitled

a guest
Dec 2nd, 2018
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 16.52 KB | None | 0 0
  1. package proyecto;
  2.  
  3. import java.sql.*;
  4. import java.text.SimpleDateFormat;
  5. import java.util.ArrayList;
  6. import java.util.Calendar;
  7. import java.util.Date;
  8. import java.util.GregorianCalendar;
  9.  
  10. public class DBConnection {
  11.  
  12.     private static Connection connection = null;
  13.  
  14.     private final static String DB_NAME = "test1";
  15.     private final static String USERNAME = "root";
  16.     private final static String PASSWORD = "password";
  17.  
  18.     public DBConnection() {
  19.         createConnection();
  20.     }
  21.  
  22.     private static boolean tableExists(String tableName) {
  23.         try {
  24.             DatabaseMetaData dbm = connection.getMetaData();
  25.             // check if "tableName" table is there
  26.             ResultSet tables = dbm.getTables(null, null, tableName, null);
  27.             if (tables.next()) {
  28.                 return true;
  29.             }
  30.         } catch (SQLException e) {
  31.             e.printStackTrace();
  32.         }
  33.  
  34.         return false;
  35.     }
  36.  
  37.     /*
  38.         cumplea�os en formato yyyy-mm-dd
  39.      */
  40.     protected void addClient(String lastName, String firstName, String email, String birthday, Long phone) {
  41.         try {
  42.             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO cliente(id_Plan, apellido, nombre, mail, fecha_nac, telefono) VALUES((SELECT id_plan FROM plan ORDER BY id_plan DESC LIMIT 1), ?, ?, ?, ?, ?)");
  43.             preparedStatement.setString(1, lastName);
  44.             preparedStatement.setString(2, firstName);
  45.             preparedStatement.setString(3, email);
  46.             preparedStatement.setString(4, birthday);
  47.             preparedStatement.setLong(5, phone);
  48.             preparedStatement.execute();
  49.             preparedStatement.close();
  50.         } catch (SQLException e) {
  51.             e.printStackTrace();
  52.         }
  53.     }
  54.  
  55.     protected void addProduct(Integer idCategory, Integer stock, Double price, String name) {
  56.         try {
  57.             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO producto(id_categoria, stock, precio, nombre) VALUES(?, ?, ?, ?)");
  58.             preparedStatement.setInt(1, idCategory);
  59.             preparedStatement.setInt(2, stock);
  60.             preparedStatement.setDouble(3, price);
  61.             preparedStatement.setString(4, name);
  62.             preparedStatement.execute();
  63.             preparedStatement.close();
  64.         } catch (SQLException e) {
  65.             e.printStackTrace();
  66.         }
  67.     }
  68.  
  69.     protected void addCategory(String name, String description) {
  70.         try {
  71.             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO categoria(nombre, descripcion) VALUES(?, ?)");
  72.             preparedStatement.setString(1, name);
  73.             preparedStatement.setString(2, description);
  74.             preparedStatement.execute();
  75.             preparedStatement.close();
  76.         } catch (SQLException e) {
  77.             e.printStackTrace();
  78.         }
  79.     }
  80.  
  81.     /*
  82.      Agregar la hora ne formato hh:mm
  83.      */
  84.     private void addClass(String dia, String hora) {
  85.         try {
  86.             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO clase(dia, hora) VALUES(?, ?)");
  87.             preparedStatement.setString(1, dia);
  88.             preparedStatement.setString(2, hora);
  89.             preparedStatement.execute();
  90.             preparedStatement.close();
  91.         } catch (SQLException e) {
  92.             e.printStackTrace();
  93.         }
  94.     }
  95.  
  96.     /*
  97.         Hora en formato hh:mm
  98.      */
  99.     protected void addPlan(String planName, String time) {
  100.         int sumDays = 0;
  101.         switch (planName.toLowerCase()) {
  102.             case "clases":
  103.             case "macroplan":
  104.             case "membresia":
  105.                 sumDays = 30;
  106.                 break;
  107.             case "visita":
  108.                 sumDays = 1;
  109.                 break;
  110.             case "becados":
  111.                 sumDays = 365;
  112.                 break;
  113.         }
  114.  
  115.         Date now = new Date();
  116.         String pattern = "yyyy-MM-dd";
  117.         SimpleDateFormat formatter = new SimpleDateFormat(pattern);
  118.         String startDate = formatter.format(now);
  119.  
  120.         Calendar c = new GregorianCalendar();
  121.         c.add(Calendar.DATE, sumDays);
  122.         Date end = c.getTime();
  123.         SimpleDateFormat formatter2 = new SimpleDateFormat(pattern);
  124.         String endDate = formatter2.format(end);
  125.  
  126.         try {
  127.             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO plan(id_clase, tipo_plan, fecha_in, fecha_fn, estatus) VALUES((SELECT id_clase FROM clase WHERE hora = ? ), ?, ?, ?, ?)");
  128.             preparedStatement.setString(1, time);
  129.             preparedStatement.setString(2, planName);
  130.             preparedStatement.setString(3, startDate);
  131.             preparedStatement.setString(4, endDate);
  132.             preparedStatement.setBoolean(5, true);
  133.             preparedStatement.execute();
  134.             preparedStatement.close();
  135.         } catch (SQLException e) {
  136.             e.printStackTrace();
  137.         }
  138.     }
  139.  
  140.     protected void addInvoice(Integer idCliente) {
  141.         try {
  142.             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO factura(id_Cliente, fecha) VALUES(?, current_date())");
  143.             preparedStatement.setInt(1, idCliente);
  144.             preparedStatement.execute();
  145.             preparedStatement.close();
  146.         } catch (SQLException e) {
  147.             e.printStackTrace();
  148.         }
  149.     }
  150.  
  151.     protected void addProductInvoice(Integer idProduct, Integer idInvoice, Integer quantity, Double price) {
  152.         try {
  153.             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO producto_factura(id_Producto, id_Factura, cantidad, precio) VALUES(?, ?, ?, ?)");
  154.             preparedStatement.setInt(1, idProduct);
  155.             preparedStatement.setInt(2, idInvoice);
  156.             preparedStatement.setInt(3, quantity);
  157.             preparedStatement.setDouble(4, price);
  158.             preparedStatement.execute();
  159.             preparedStatement.close();
  160.         } catch (SQLException e) {
  161.             e.printStackTrace();
  162.         }
  163.     }
  164.  
  165.     protected void updateClient(Integer idPlan, String lastName, String firstName, String email, String birthday, Long phone) {
  166.         String updateClient = "UPDATE cliente" +
  167.                 "        SET id_plan = " + idPlan + ", apellido = '" + lastName + "', nombre = '" + firstName + "', mail = '" +
  168.                 email + "', fecha_nac = '" + birthday + "', telefono = " + phone + "," +
  169.                 "        WHERE nombre = '" + firstName + "'";
  170.  
  171.         executeQuery(updateClient);
  172.     }
  173.  
  174.     private static void createTables() {
  175.         String tableClass = "CREATE TABLE clase(" +
  176.                 "    id_Clase    int not null primary key auto_increment," +
  177.                 "    dia         varchar(20)," +
  178.                 "    hora        time" +
  179.                 "    )";
  180.  
  181.         String tablePlan = "CREATE TABLE plan(" +
  182.                 "    id_Plan     int not null primary key auto_increment," +
  183.                 "    id_Clase    int not null," +
  184.                 "    tipo_plan   char(10)," +
  185.                 "    fecha_in    date," +
  186.                 "    fecha_fn    date," +
  187.                 "    estatus     bool," +
  188.                 "    foreign key (id_Clase) references Clase(id_Clase)" +
  189.                 "    )";
  190.  
  191.         String tableClient = "CREATE TABLE cliente(" +
  192.                 "    id_Cliente  int not null primary key auto_increment," +
  193.                 "    id_Plan     int not null ," +
  194.                 "    apellido    varchar(30)," +
  195.                 "    nombre      varchar(20)," +
  196.                 "    mail        varchar (25)," +
  197.                 "    fecha_nac   date," +
  198.                 "    telefono    numeric(10,0)," +
  199.                 "    foreign key (id_Plan) references Plan(id_Plan)" +
  200.                 "    )";
  201.  
  202.         String tableCategory = "CREATE TABLE categoria(" +
  203.                 "    id_Categoria    int not null primary key auto_increment," +
  204.                 "    nombre          varchar(20)," +
  205.                 "    descripcion     varchar(30)" +
  206.                 ")";
  207.  
  208.         String tableProduct = "CREATE TABLE producto(" +
  209.                 "    id_Producto int not null primary key auto_increment," +
  210.                 "    id_Categoria int not null," +
  211.                 "    stock       int," +
  212.                 "    precio      decimal (19,4)," +
  213.                 "    nombre      varchar(20)," +
  214.                 "    foreign key (id_Categoria) references Categoria(id_Categoria)" +
  215.                 "    )";
  216.  
  217.         String tableInvoice = "CREATE TABLE factura(" +
  218.                 "    id_Factura  int not null primary key auto_increment," +
  219.                 "    id_Cliente  int not null," +
  220.                 "    fecha       date," +
  221.                 "    foreign key (id_Cliente) references Cliente(id_Cliente)" +
  222.                 "    )";
  223.  
  224.         String tableProductInvoice = "CREATE TABLE Producto_Factura(" +
  225.                 "    id_Producto_Factura int not null primary key auto_increment," +
  226.                 "    id_Producto         int not null," +
  227.                 "    id_Factura          int not null," +
  228.                 "    cantidad            int," +
  229.                 "    precio              decimal(19,4)" +
  230.                 ");";
  231.  
  232.         executeQuery(tableClass);
  233.         executeQuery(tablePlan);
  234.         executeQuery(tableClient);
  235.         executeQuery(tableCategory);
  236.         executeQuery(tableProduct);
  237.         executeQuery(tableInvoice);
  238.         executeQuery(tableProductInvoice);
  239.     }
  240.  
  241.     private static void executeQuery(String sql) {
  242.         try {
  243.             Statement statement = connection.createStatement();
  244.             statement.executeUpdate(sql);
  245.             statement.close();
  246.         } catch (SQLException e) {
  247.             e.printStackTrace();
  248.         }
  249.     }
  250.  
  251.  
  252.     private static void createConnection() {
  253.         try {
  254.             Class.forName("com.mysql.cj.jdbc.Driver");
  255.             connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + DB_NAME +
  256.                             "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC",
  257.                     USERNAME, PASSWORD);
  258.             System.out.println("Database Connection Successful");
  259.  
  260.             if (!tableExists("cliente")) createTables();
  261.  
  262.         } catch (ClassNotFoundException | SQLException e) {
  263.             e.printStackTrace();
  264.         }
  265.     }
  266.  
  267.     protected void closeConnection() {
  268.         try {
  269. //            if (rs != null) rs.close();
  270. //            if (statement != null) statement.close();
  271.             if (connection != null) connection.close();
  272.         } catch (SQLException e) {
  273.             e.printStackTrace();
  274.         }
  275.     }
  276.  
  277.     protected ArrayList<Cliente> getClients() {
  278.         int resPlanID = 0;
  279.  
  280.         ArrayList<Cliente> clients = new ArrayList<>();
  281.  
  282.         try {
  283.             Statement st1 = connection.createStatement();
  284.             ResultSet rs1 = st1.executeQuery("SELECT * FROM cliente");
  285.  
  286.             while (rs1.next()) {
  287.                 resPlanID = rs1.getInt("id_plan"); // Se pone el indice de la col o el nombre de esta
  288.                 Cliente cliente = new Cliente();
  289.  
  290.                 cliente.setId(String.valueOf(rs1.getInt("id_cliente")));
  291.                 cliente.setLastname(rs1.getString("apellido"));
  292.                 cliente.setName(rs1.getString("nombre"));
  293.                 cliente.setMail(rs1.getString("mail"));
  294.                 cliente.setFechaNacimiento(rs1.getString("fecha_nac"));
  295.                 cliente.setTelefono(String.valueOf(rs1.getLong("telefono")));
  296.  
  297.                 Plan plan = getPlan(resPlanID);
  298.                 cliente.setPlan(plan.getPlanType());
  299.                 cliente.setFechaInicio(plan.getStart());
  300.                 cliente.setFechaFin(plan.getEnd());
  301.                 cliente.setEstatus((plan.isStatus() ? "Activo" : "Inactivo"));
  302.                 cliente.setHora(plan.getHour());
  303.  
  304.                 clients.add(cliente);
  305.             }
  306.  
  307.             st1.close();
  308.             rs1.close();
  309.         } catch (SQLException e) {
  310.             e.printStackTrace();
  311.         }
  312.  
  313.         return clients;
  314.  
  315.     }
  316.  
  317.     protected Cliente getClientByName(String firstName, String lastName) {
  318.         int resPlanID = 0;
  319.  
  320.         Cliente cliente = new Cliente();
  321.  
  322.  
  323.         try {
  324.             Statement st1 = connection.createStatement();
  325.             ResultSet rs1 = st1.executeQuery("SELECT id_Plan, apellido, nombre, mail, fecha_nac, telefono FROM cliente WHERE apellido = '" + lastName + "' AND nombre = '" + firstName + "' ");
  326.  
  327.             while (rs1.next()) {
  328.                 resPlanID = rs1.getInt("id_plan"); // Se pone el indice de la col o el nombre de esta
  329.                 cliente.setLastname(rs1.getString("apellido"));
  330.                 cliente.setName(rs1.getString("nombre"));
  331.                 cliente.setMail(rs1.getString("mail"));
  332.                 cliente.setFechaNacimiento(rs1.getString("fecha_nac"));
  333.                 cliente.setTelefono(String.valueOf(rs1.getLong("telefono")));
  334.             }
  335.  
  336.             st1.close();
  337.             rs1.close();
  338.         } catch (SQLException e) {
  339.             e.printStackTrace();
  340.         }
  341.  
  342.         Plan plan = getPlan(resPlanID);
  343.         cliente.setPlan(plan.getPlanType());
  344.         cliente.setFechaInicio(plan.getStart());
  345.         cliente.setFechaFin(plan.getEnd());
  346.         cliente.setEstatus((plan.isStatus() ? "Activo" : "Inactivo"));
  347.         cliente.setHora(plan.getHour());
  348.  
  349.         return cliente;
  350.     }
  351.  
  352.     protected Cliente getClientByID(String id) {
  353.         int resPlanID = 0;
  354.  
  355.         Cliente cliente = new Cliente();
  356.  
  357.         try {
  358.             Statement st1 = connection.createStatement();
  359.             ResultSet rs1 = st1.executeQuery("SELECT id_Plan, apellido, nombre, mail, fecha_nac, telefono FROM cliente WHERE id_cliente = '" + id + "'");
  360.  
  361.             while (rs1.next()) {
  362.                 resPlanID = rs1.getInt("id_plan"); // Se pone el indice de la col o el nombre de esta
  363.                 cliente.setLastname(rs1.getString("apellido"));
  364.                 cliente.setName(rs1.getString("nombre"));
  365.                 cliente.setMail(rs1.getString("mail"));
  366.                 cliente.setFechaNacimiento(rs1.getString("fecha_nac"));
  367.                 cliente.setTelefono(String.valueOf(rs1.getLong("telefono")));
  368.             }
  369.  
  370.             st1.close();
  371.             rs1.close();
  372.         } catch (SQLException e) {
  373.             e.printStackTrace();
  374.         }
  375.  
  376.         Plan plan = getPlan(resPlanID);
  377.         cliente.setPlan(plan.getPlanType());
  378.         cliente.setFechaInicio(plan.getStart());
  379.         cliente.setFechaFin(plan.getEnd());
  380.         cliente.setEstatus((plan.isStatus() ? "Activo" : "Inactivo"));
  381.         cliente.setHora(plan.getHour());
  382.  
  383.         return cliente;
  384.     }
  385.  
  386.     private Plan getPlan(Integer planID) {
  387.         int resClassID = 0;
  388.         Plan plan = new Plan();
  389.  
  390.         try {
  391.             Statement st1 = connection.createStatement();
  392.             ResultSet rs1 = st1.executeQuery("SELECT id_Clase, tipo_plan, fecha_in, fecha_fn, estatus FROM plan WHERE id_plan = '" + planID + "'");
  393.  
  394.             while (rs1.next()) {
  395.                 resClassID = rs1.getInt("id_clase"); // Se pone el indice de la col o el nombre de esta
  396.                 plan.setPlanType(rs1.getString("tipo_plan"));
  397.                 plan.setStart(rs1.getString("fecha_in"));
  398.                 plan.setEnd(rs1.getString("fecha_fn"));
  399.                 plan.setStatus(rs1.getBoolean("estatus"));
  400.             }
  401.             st1.close();
  402.             rs1.close();
  403.         } catch (SQLException e) {
  404.             e.printStackTrace();
  405.         }
  406.  
  407.         Clase clase = getClass(resClassID);
  408.  
  409.         plan.setDay(clase.getDay());
  410.         plan.setHour(clase.getHour());
  411.  
  412.         return plan;
  413.     }
  414.  
  415.     private Clase getClass(Integer classID) {
  416.         String resDay = null;
  417.         String resHour = null;
  418.  
  419.         try {
  420.             Statement st1 = connection.createStatement();
  421.             ResultSet rs1 = st1.executeQuery("SELECT dia, hora FROM clase WHERE id_clase = '" + classID + "'");
  422.  
  423.             while (rs1.next()) {
  424.                 resDay = rs1.getString("dia"); // Se pone el indice de la col o el nombre de esta
  425.                 resHour = rs1.getString("hora");
  426.             }
  427.             st1.close();
  428.             rs1.close();
  429.         } catch (SQLException e) {
  430.             e.printStackTrace();
  431.         }
  432.  
  433.         return new Clase(resDay, resHour);
  434.     }
  435.  
  436.  
  437.  
  438. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement