Advertisement
Guest User

Untitled

a guest
Dec 2nd, 2018
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 16.83 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 = "test3";
  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.         return false;
  34.  
  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.     protected 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 "clase":
  103.             case "macroplan":
  104.             case "membresia":
  105.                 sumDays = 30;
  106.                 break;
  107.             case "visita":
  108.                 sumDays = 1;
  109.                 break;
  110.             case "becado":
  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.             System.out.println(tableExists("cliente"));
  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.         ArrayList<Cliente> clients = new ArrayList<>();
  280.  
  281.         try {
  282.             Statement st1 = connection.createStatement();
  283.             ResultSet rs1 = st1.executeQuery("SELECT * FROM cliente");
  284.  
  285.             getClientsFromDatabase(clients, rs1);
  286.  
  287.             st1.close();
  288.             rs1.close();
  289.         } catch (SQLException e) {
  290.             e.printStackTrace();
  291.         }
  292.  
  293.         return clients;
  294.     }
  295.  
  296.     protected ArrayList<Cliente> getClientByName(String name) {
  297.         ArrayList<Cliente> clients = new ArrayList<>();
  298.  
  299.         try {
  300.             Statement st1 = connection.createStatement();
  301.             ResultSet rs1 = st1.executeQuery("SELECT * FROM cliente WHERE nombre = '" + name + "'");
  302.  
  303.             getClientsFromDatabase(clients, rs1);
  304.  
  305.             st1.close();
  306.             rs1.close();
  307.         } catch (SQLException e) {
  308.             e.printStackTrace();
  309.         }
  310.  
  311.         return clients;
  312.     }
  313.  
  314.     protected ArrayList<Cliente> getClientByFullName(String firstName, String lastName) {
  315.         ArrayList<Cliente> clients = new ArrayList<>();
  316.  
  317.         try {
  318.             Statement st1 = connection.createStatement();
  319.             ResultSet rs1 = st1.executeQuery("SELECT * FROM cliente WHERE apellido = '" + lastName + "' AND nombre = '" + firstName + "' ");
  320.  
  321.             getClientsFromDatabase(clients, rs1);
  322.  
  323.             st1.close();
  324.             rs1.close();
  325.         } catch (SQLException e) {
  326.             e.printStackTrace();
  327.         }
  328.  
  329.         return clients;
  330.     }
  331.  
  332.     private void getClientsFromDatabase(ArrayList<Cliente> clients, ResultSet rs1) throws SQLException {
  333.         int resPlanID;
  334.         while (rs1.next()) {
  335.             resPlanID = rs1.getInt("id_plan"); // Se pone el indice de la col o el nombre de esta
  336.             Cliente cliente = new Cliente();
  337.  
  338.             cliente.setId(String.valueOf(rs1.getInt("id_cliente")));
  339.             cliente.setLastname(rs1.getString("apellido"));
  340.             cliente.setName(rs1.getString("nombre"));
  341.             cliente.setMail(rs1.getString("mail"));
  342.             cliente.setFechaNacimiento(rs1.getString("fecha_nac"));
  343.             cliente.setTelefono(String.valueOf(rs1.getLong("telefono")));
  344.  
  345.             Plan plan = getPlan(resPlanID);
  346.             cliente.setPlan(plan.getPlanType());
  347.             cliente.setFechaInicio(plan.getStart());
  348.             cliente.setFechaFin(plan.getEnd());
  349.             cliente.setEstatus((plan.isStatus() ? "Activo" : "Inactivo"));
  350.             cliente.setHora(plan.getHour());
  351.  
  352.             clients.add(cliente);
  353.         }
  354.     }
  355.  
  356.     protected Cliente getClientByID(String id) {
  357.         int resPlanID = 0;
  358.  
  359.         Cliente cliente = new Cliente();
  360.  
  361.         try {
  362.             Statement st1 = connection.createStatement();
  363.             ResultSet rs1 = st1.executeQuery("SELECT id_Plan, apellido, nombre, mail, fecha_nac, telefono FROM cliente WHERE id_cliente = '" + id + "'");
  364.  
  365.             while (rs1.next()) {
  366.                 resPlanID = rs1.getInt("id_plan"); // Se pone el indice de la col o el nombre de esta
  367.                 cliente.setLastname(rs1.getString("apellido"));
  368.                 cliente.setName(rs1.getString("nombre"));
  369.                 cliente.setMail(rs1.getString("mail"));
  370.                 cliente.setFechaNacimiento(rs1.getString("fecha_nac"));
  371.                 cliente.setTelefono(String.valueOf(rs1.getLong("telefono")));
  372.             }
  373.  
  374.             st1.close();
  375.             rs1.close();
  376.         } catch (SQLException e) {
  377.             e.printStackTrace();
  378.         }
  379.  
  380.         Plan plan = getPlan(resPlanID);
  381.         cliente.setPlan(plan.getPlanType());
  382.         cliente.setFechaInicio(plan.getStart());
  383.         cliente.setFechaFin(plan.getEnd());
  384.         cliente.setEstatus((plan.isStatus() ? "Activo" : "Inactivo"));
  385.         cliente.setHora(plan.getHour());
  386.  
  387.         return cliente;
  388.     }
  389.  
  390.     private Plan getPlan(Integer planID) {
  391.         int resClassID = 0;
  392.         Plan plan = new Plan();
  393.  
  394.         try {
  395.             Statement st1 = connection.createStatement();
  396.             ResultSet rs1 = st1.executeQuery("SELECT id_Clase, tipo_plan, fecha_in, fecha_fn, estatus FROM plan WHERE id_plan = '" + planID + "'");
  397.  
  398.             while (rs1.next()) {
  399.                 resClassID = rs1.getInt("id_clase"); // Se pone el indice de la col o el nombre de esta
  400.                 plan.setPlanType(rs1.getString("tipo_plan"));
  401.                 plan.setStart(rs1.getString("fecha_in"));
  402.                 plan.setEnd(rs1.getString("fecha_fn"));
  403.                 plan.setStatus(rs1.getBoolean("estatus"));
  404.             }
  405.             st1.close();
  406.             rs1.close();
  407.         } catch (SQLException e) {
  408.             e.printStackTrace();
  409.         }
  410.  
  411.         Clase clase = getClass(resClassID);
  412.  
  413.         plan.setDay(clase.getDay());
  414.         plan.setHour(clase.getHour());
  415.  
  416.         return plan;
  417.     }
  418.  
  419.     private Clase getClass(Integer classID) {
  420.         String resDay = null;
  421.         String resHour = null;
  422.  
  423.         try {
  424.             Statement st1 = connection.createStatement();
  425.             ResultSet rs1 = st1.executeQuery("SELECT dia, hora FROM clase WHERE id_clase = '" + classID + "'");
  426.  
  427.             while (rs1.next()) {
  428.                 resDay = rs1.getString("dia"); // Se pone el indice de la col o el nombre de esta
  429.                 resHour = rs1.getString("hora");
  430.             }
  431.             st1.close();
  432.             rs1.close();
  433.         } catch (SQLException e) {
  434.             e.printStackTrace();
  435.         }
  436.  
  437.         return new Clase(resDay, resHour);
  438.     }
  439.  
  440.     protected boolean tableExistsNonStatic(String tableName) {
  441.         try {
  442.             DatabaseMetaData dbm = connection.getMetaData();
  443.             // check if "tableName" table is there
  444.             ResultSet tables = dbm.getTables(null, null, tableName, null);
  445.             if (tables.next()) {
  446.                 return true;
  447.             }
  448.         } catch (SQLException e) {
  449.             e.printStackTrace();
  450.         }
  451.         return false;
  452.  
  453.     }
  454.  
  455.  
  456. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement