Advertisement
Guest User

Untitled

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