Advertisement
Guest User

Untitled

a guest
Dec 1st, 2018
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.33 KB | None | 0 0
  1. package proyecto;
  2.  
  3. import java.sql.*;
  4. import java.text.SimpleDateFormat;
  5. import java.util.Calendar;
  6. import java.util.Date;
  7. import java.util.GregorianCalendar;
  8.  
  9. public class DBConnection {
  10.  
  11.     private static Connection connection = null;
  12.  
  13.     private final static String DB_NAME = "pae";
  14.     private final static String USERNAME = "root";
  15.     private final static String PASSWORD = "password";
  16.  
  17.     public DBConnection() {
  18.         createConnection();
  19.     }
  20.  
  21.     private static boolean tableExists(String tableName) {
  22.         try {
  23.             DatabaseMetaData dbm = connection.getMetaData();
  24.             // check if "tableName" table is there
  25.             ResultSet tables = dbm.getTables(null, null, tableName, null);
  26.             if (tables.next()) {
  27.                 return true;
  28.             }
  29.         } catch (SQLException e) {
  30.             e.printStackTrace();
  31.         }
  32.  
  33.         return false;
  34.     }
  35.  
  36.     /*
  37.         cumpleaños en formato yyyy-mm-dd
  38.      */
  39.     protected void addClient(String lastName, String firstName, String email, String birthday, Long phone) {
  40.         try {
  41.             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), ?, ?, ?, ?, ?)");
  42.             preparedStatement.setString(1, lastName);
  43.             preparedStatement.setString(2, firstName);
  44.             preparedStatement.setString(3, email);
  45.             preparedStatement.setString(4, birthday);
  46.             preparedStatement.setLong(5, phone);
  47.             preparedStatement.execute();
  48.             preparedStatement.close();
  49.         } catch (SQLException e) {
  50.             e.printStackTrace();
  51.         }
  52.     }
  53.  
  54.     protected void addProduct(Integer idCategory, Integer stock, Double price, String name) {
  55.         try {
  56.             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO producto(id_categoria, stock, precio, nombre) VALUES(?, ?, ?, ?)");
  57.             preparedStatement.setInt(1, idCategory);
  58.             preparedStatement.setInt(2, stock);
  59.             preparedStatement.setDouble(3, price);
  60.             preparedStatement.setString(4, name);
  61.             preparedStatement.execute();
  62.             preparedStatement.close();
  63.         } catch (SQLException e) {
  64.             e.printStackTrace();
  65.         }
  66.     }
  67.  
  68.     protected void addCategory(String name, String description) {
  69.         try {
  70.             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO categoria(nombre, descripcion) VALUES(?, ?)");
  71.             preparedStatement.setString(1, name);
  72.             preparedStatement.setString(2, description);
  73.             preparedStatement.execute();
  74.             preparedStatement.close();
  75.         } catch (SQLException e) {
  76.             e.printStackTrace();
  77.         }
  78.     }
  79.  
  80.     /*
  81.      Agregar la hora ne formato hh:mm
  82.      */
  83.     private void addClass(String dia, String hora) {
  84.         try {
  85.             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO clase(dia, hora) VALUES(?, ?)");
  86.             preparedStatement.setString(1, dia);
  87.             preparedStatement.setString(2, hora);
  88.             preparedStatement.execute();
  89.             preparedStatement.close();
  90.         } catch (SQLException e) {
  91.             e.printStackTrace();
  92.         }
  93.     }
  94.  
  95.     /*
  96.         Hora en formato hh:mm
  97.      */
  98.     protected void addPlan(String planName, String time) {
  99.         int sumDays = 0;
  100.         switch (planName.toLowerCase()) {
  101.             case "clases":
  102.             case "macroplan":
  103.             case "membresia":
  104.                 sumDays = 30;
  105.                 break;
  106.             case "visita":
  107.                 sumDays = 1;
  108.                 break;
  109.             case "becados":
  110.                 sumDays = 365;
  111.                 break;
  112.         }
  113.  
  114.         Date now = new Date();
  115.         String pattern = "yyyy-MM-dd";
  116.         SimpleDateFormat formatter = new SimpleDateFormat(pattern);
  117.         String startDate = formatter.format(now);
  118.  
  119.         Calendar c=new GregorianCalendar();
  120.         c.add(Calendar.DATE, sumDays);
  121.         Date end = c.getTime();
  122.         SimpleDateFormat formatter2 = new SimpleDateFormat(pattern);
  123.         String endDate = formatter2.format(end);
  124.  
  125.         try {
  126.             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO plan(tipo_plan, fecha_in, fecha_fn, estatus) VALUES((SELECT id_clase FROM clase WHERE hora = ? ), ?, ?, ?, ?)");
  127.             preparedStatement.setString(1, time);
  128.             preparedStatement.setString(2, planName);
  129.             preparedStatement.setString(3, startDate);
  130.             preparedStatement.setString(4, endDate);
  131.             preparedStatement.setBoolean(5, true);
  132.             preparedStatement.execute();
  133.             preparedStatement.close();
  134.         } catch (SQLException e) {
  135.             e.printStackTrace();
  136.         }
  137.     }
  138.  
  139.     protected void addInvoice(Integer idCliente) {
  140.         try {
  141.             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO factura(id_Cliente, fecha) VALUES(?, current_date())");
  142.             preparedStatement.setInt(1, idCliente);
  143.             preparedStatement.execute();
  144.             preparedStatement.close();
  145.         } catch (SQLException e) {
  146.             e.printStackTrace();
  147.         }
  148.     }
  149.  
  150.     protected void addProductInvoice(Integer idProduct, Integer idInvoice, Integer quantity, Double price) {
  151.         try {
  152.             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO producto_factura(id_Producto, id_Factura, cantidad, precio) VALUES(?, ?, ?, ?)");
  153.             preparedStatement.setInt(1, idProduct);
  154.             preparedStatement.setInt(2, idInvoice);
  155.             preparedStatement.setInt(3, quantity);
  156.             preparedStatement.setDouble(4, price);
  157.             preparedStatement.execute();
  158.             preparedStatement.close();
  159.         } catch (SQLException e) {
  160.             e.printStackTrace();
  161.         }
  162.     }
  163.  
  164.     protected void updateClient(Integer idPlan, String lastName, String firstName, String email, String birthday, Long phone) {
  165.         String updateClient = "UPDATE cliente" +
  166.                 "        SET id_plan = " + idPlan + ", apellido = '" + lastName + "', nombre = '" + firstName + "', mail = '" +
  167.                 email + "', fecha_nac = '" + birthday + "', telefono = " + phone + "," +
  168.                 "        WHERE nombre = '" + firstName + "'";
  169.  
  170.         executeQuery(updateClient);
  171.     }
  172.  
  173.     private static void createTables() {
  174.         String tableClass = "CREATE TABLE clase(\n" +
  175.                 "    id_Clase    int not null primary key auto_increment,\n" +
  176.                 "    dia         varchar(20),\n" +
  177.                 "    hora        time\n" +
  178.                 "    )";
  179.  
  180.         String tablePlan = "CREATE TABLE plan(\n" +
  181.                 "    id_Plan     int not null primary key auto_increment,\n" +
  182.                 "    id_Clase    int not null,\n" +
  183.                 "    tipo_plan   char(10),\n" +
  184.                 "    fecha_in    date,\n" +
  185.                 "    fecha_fn    date,\n" +
  186.                 "    estatus     bool,\n" +
  187.                 "    foreign key (id_Clase) references Clase(id_Clase)\n" +
  188.                 "    )";
  189.  
  190.         String tableClient = "CREATE TABLE cliente(\n" +
  191.                 "    id_Cliente  int not null primary key auto_increment,\n" +
  192.                 "    id_Plan     int not null ,\n" +
  193.                 "    apellido    varchar(30),\n" +
  194.                 "    nombre      varchar(20),\n" +
  195.                 "    mail        varchar (25),\n" +
  196.                 "    fecha_nac   date,\n" +
  197.                 "    telefono    numeric(10,0),\n" +
  198.                 "    foreign key (id_Plan) references Plan(id_Plan)\n" +
  199.                 "    )";
  200.  
  201.         String tableCategory = "CREATE TABLE categoria(\n" +
  202.                 "    id_Categoria    int not null primary key auto_increment,\n" +
  203.                 "    nombre          varchar(20),\n" +
  204.                 "    descripcion     varchar(30)\n" +
  205.                 ")";
  206.  
  207.         String tableProduct = "CREATE TABLE producto(\n" +
  208.                 "    id_Producto int not null primary key auto_increment,\n" +
  209.                 "    id_Categoria int not null,\n" +
  210.                 "    stock       int,\n" +
  211.                 "    precio      decimal (19,4),\n" +
  212.                 "    nombre      varchar(20),\n" +
  213.                 "    foreign key (id_Categoria) references Categoria(id_Categoria)\n" +
  214.                 "    )";
  215.  
  216.         String tableInvoice = "CREATE TABLE factura(\n" +
  217.                 "    id_Factura  int not null primary key auto_increment,\n" +
  218.                 "    id_Cliente  int not null,\n" +
  219.                 "    fecha       date,\n" +
  220.                 "    foreign key (id_Cliente) references Cliente(id_Cliente)\n" +
  221.                 "    )";
  222.  
  223.         String tableProductInvoice = "CREATE TABLE Producto_Factura(\n" +
  224.                 "    id_Producto_Factura int not null primary key auto_increment,\n" +
  225.                 "    id_Producto         int not null,\n" +
  226.                 "    id_Factura          int not null,\n" +
  227.                 "    cantidad            int,\n" +
  228.                 "    precio              decimal(19,4)\n" +
  229.                 ");";
  230.  
  231.         executeQuery(tableClass);
  232.         executeQuery(tablePlan);
  233.         executeQuery(tableClient);
  234.         executeQuery(tableCategory);
  235.         executeQuery(tableProduct);
  236.         executeQuery(tableInvoice);
  237.         executeQuery(tableProductInvoice);
  238.     }
  239.  
  240.     private static void executeQuery(String sql) {
  241.         try {
  242.             Statement statement = connection.createStatement();
  243.             statement.executeUpdate(sql);
  244.             statement.close();
  245.         } catch (SQLException e) {
  246.             e.printStackTrace();
  247.         }
  248.     }
  249.  
  250.  
  251.     private static void createConnection() {
  252.         try {
  253.             Class.forName("com.mysql.cj.jdbc.Driver");
  254.             connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + DB_NAME +
  255.                             "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC",
  256.                     USERNAME, PASSWORD);
  257.             System.out.println("Database Connection Successful");
  258.  
  259.             if (!tableExists("cliente")) createTables();
  260.  
  261.         } catch (ClassNotFoundException | SQLException e) {
  262.             e.printStackTrace();
  263.         }
  264.     }
  265.  
  266.     protected void closeConnection() {
  267.         try {
  268. //            if (rs != null) rs.close();
  269. //            if (statement != null) statement.close();
  270.             if (connection != null) connection.close();
  271.         } catch (SQLException e) {
  272.             e.printStackTrace();
  273.         }
  274.     }
  275. //
  276. //    protected void getClients() {
  277. //        try {
  278. //            Statement st1 = connection.createStatement();
  279. //            ResultSet rs1 = st1.executeQuery("SELECT * FROM users");
  280. //
  281. //            while (rs1.next()) {
  282. //                String name = rs1.getString("name"); // Se pone el indice de la col o el nombre de esta
  283. //                System.out.println(name);
  284. //            }
  285. //            st1.close();
  286. //            rs1.close();
  287. //        } catch (SQLException e) {
  288. //            e.printStackTrace();
  289. //        }
  290. //    }
  291.  
  292.  
  293. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement