HarrJ

Day 22

Aug 25th, 2023 (edited)
1,729
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.62 KB | None | 0 0
  1. package connecting_to_db;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import javax.swing.table.DefaultTableModel;
  8.  
  9. public class CrudProductListD21 {
  10.     private String address = "jdbc:mysql://127.0.0.1:3306/db_mng_batch5?zeroDateTimeBehavior=convertToNull";
  11.     private String userName = "root";
  12.     private String passWord = "";
  13.    
  14.     public void getAllCategory(){
  15.         String sqlQuery = "SELECT * FROM tbl_category_list ORDER BY fld_aisle_num";
  16.        
  17.         try {
  18.             Connection conn = DriverManager.getConnection(
  19.                     address,userName,passWord);
  20.             PreparedStatement stmt = conn.prepareStatement(sqlQuery);
  21.            
  22.             ResultSet rs = stmt.executeQuery();
  23.            
  24.             while (rs.next()) {                
  25.                 System.out.printf("%3s - ",rs.getString("fld_catid"));
  26.                 System.out.printf("%-20s%n",rs.getString("fld_catname"));
  27. //                System.out.printf("%-3s%n",rs.getString("fld_aisle_num"));
  28.             }
  29.            
  30.             conn.close();
  31.         } catch (Exception e) {
  32.             System.out.println(e.getMessage());
  33.         }
  34.     }
  35.    
  36.     public void getAllRows(){
  37.         String sqlQuery = "SELECT * FROM tbl_product_list ORDER BY fld_pid DESC LIMIT 0,15";
  38.         // REMOVE  ORDER BY fld_pid DESC LIMIT 0,15  TO SHOW ALL ROWS
  39.         try {
  40.             Connection conn = DriverManager.getConnection(
  41.                     address,userName,passWord);
  42.             PreparedStatement stmt = conn.prepareStatement(sqlQuery);
  43.            
  44.             ResultSet rs = stmt.executeQuery();
  45.            
  46.             while (rs.next()) {                
  47.                 System.out.printf("%3s | ",rs.getString(1));
  48.                 System.out.printf("%-35s | ",rs.getString(2));
  49.                 System.out.printf("%8.2f | ",rs.getDouble(3));
  50.                 System.out.printf("%-35s | ",rs.getString(4));
  51.                 System.out.printf("%-3s%n",rs.getString(5));
  52.             }
  53.            
  54.             conn.close();
  55.         } catch (Exception e) {
  56.             System.out.println(e.getMessage());
  57.         }
  58.     }
  59.    
  60.     public void getAllRows(String searchName){
  61.         String sqlQuery = "SELECT * FROM tbl_product_list WHERE LOWER(fld_pname) LIKE LOWER(?)";
  62.        
  63.         searchName = "%"+searchName+"%";
  64.         // REMOVE  ORDER BY fld_pid DESC LIMIT 0,15  TO SHOW ALL ROWS
  65.         try {
  66.             Connection conn = DriverManager.getConnection(
  67.                     address,userName,passWord);
  68.             PreparedStatement stmt = conn.prepareStatement(sqlQuery);
  69.            
  70.             stmt.setString(1, searchName);
  71.             ResultSet rs = stmt.executeQuery();
  72.            
  73.             while (rs.next()) {                
  74.                 System.out.printf("%3s | ",rs.getString(1));
  75.                 System.out.printf("%-35s | ",rs.getString(2));
  76.                 System.out.printf("%8.2f | ",rs.getDouble(3));
  77.                 System.out.printf("%-35s | ",rs.getString(4));
  78.                 System.out.printf("%-3s%n",rs.getString(5));
  79.             }
  80.            
  81.             conn.close();
  82.         } catch (Exception e) {
  83.             System.out.println(e.getMessage());
  84.         }
  85.     }
  86.    
  87.     public int addNewRow(String pName, double pPrice, String pManufacturer, int catId) {
  88.         int rowsAffected = 0;
  89.         String sqlQuery = "INSERT INTO tbl_product_list ( fld_pname, fld_price, fld_manufacturer, fld_catid) VALUES (?, ?, ?, ?);";
  90.         try {
  91.             Connection conn = DriverManager.getConnection(
  92.                     address,userName,passWord);
  93.             PreparedStatement stmt = conn.prepareStatement(sqlQuery);
  94.            
  95.             stmt.setString(1, pName);
  96.             stmt.setDouble(2, pPrice);
  97.             stmt.setString(3, pManufacturer);
  98.             stmt.setInt(4, catId);
  99.            
  100.             rowsAffected = stmt.executeUpdate();
  101.            
  102.             conn.close();
  103.         } catch (Exception e) {
  104.             System.out.println(e.getMessage());
  105.         }
  106.         return rowsAffected;
  107.     }
  108.    
  109.     public int updateRow(String pName, double pPrice, String pManufacturer, int catId, int prodId) {
  110.         int rowsAffected = 0;
  111.         String sqlQuery = "UPDATE tbl_product_list SET fld_pname=? ,fld_price=?"
  112.                 + " ,fld_manufacturer=?,fld_catid=?"
  113.                 + " WHERE fld_pid=?";
  114.        
  115.         try {
  116.             Connection conn = DriverManager.getConnection(
  117.                     address,userName,passWord);
  118.             PreparedStatement stmt = conn.prepareStatement(sqlQuery);
  119.            
  120.             stmt.setString(1, pName);
  121.             stmt.setDouble(2, pPrice);
  122.             stmt.setString(3, pManufacturer);
  123.             stmt.setInt(4, catId);
  124.             stmt.setInt(5, prodId);
  125.            
  126.             rowsAffected = stmt.executeUpdate();
  127.            
  128.             conn.close();
  129.         } catch (Exception e) {
  130.             System.out.println(e.getMessage());
  131.         }
  132.         return rowsAffected;
  133.     }
  134.    
  135.     public int deleteProductRow(int pid) {
  136.         int rowsAffected = 0;String sqlQuery = "DELETE FROM tbl_product_list WHERE fld_pid = ?";
  137.        
  138.         try {
  139.             Connection conn = DriverManager.getConnection(
  140.                     address,userName,passWord);
  141.             PreparedStatement stmt = conn.prepareStatement(sqlQuery);
  142.            
  143.             stmt.setInt(1, pid);
  144.            
  145.             rowsAffected = stmt.executeUpdate();
  146.            
  147.             conn.close();
  148.         } catch (Exception e) {
  149.             System.out.println(e.getMessage());
  150.         }
  151.        
  152.         return rowsAffected;
  153.     }
  154. // ------- METHODS FORM USAGE -------
  155.     public String[] setCatComboBox() {
  156.         boolean isComplete = false;
  157.         String[] returnedValue;
  158.         String[] dummy = {"1|sample"};
  159.         String[] categoryList;
  160.         int count=0;
  161.         String sqlQuery = "SELECT COUNT(*) FROM tbl_category_list";
  162.         try {
  163.             Connection conn = DriverManager.getConnection(
  164.                     address,userName,passWord);
  165.             PreparedStatement stmt = conn.prepareStatement(sqlQuery);
  166.             ResultSet rs = stmt.executeQuery();
  167.             rs.next();
  168.             categoryList = new String[rs.getInt(1)];
  169.             System.out.println(categoryList.length);
  170. //            conn.close();
  171.             sqlQuery = "SELECT * FROM tbl_category_list";
  172.  
  173.             try {
  174.                 PreparedStatement stmt1 = conn.prepareStatement(sqlQuery);
  175.  
  176.                 ResultSet rs2 = stmt1.executeQuery();
  177.  
  178.                 while (rs2.next()) {
  179.                     categoryList[count] = rs2.getString(1) + "|" + rs2.getString(2);
  180.                     count++;
  181.                 }
  182.                 conn.close();
  183.                 return categoryList;
  184.             } catch (Exception e) {
  185.                 System.out.println("t2"+e.getMessage());
  186.             }
  187.         } catch (Exception e) {
  188.             System.out.println("t1"+e.getMessage());
  189.         }
  190.         return dummy;
  191.     }
  192.    
  193.     public void setRowsToTable(DefaultTableModel tableModel){
  194.         String sqlQuery = "SELECT * FROM tbl_product_list ORDER BY fld_pid";
  195.         // REMOVE  ORDER BY fld_pid DESC LIMIT 0,15  TO SHOW ALL ROWS
  196.         try {
  197.             Connection conn = DriverManager.getConnection(
  198.                     address,userName,passWord);
  199.             PreparedStatement stmt = conn.prepareStatement(sqlQuery);
  200.            
  201.             ResultSet rs = stmt.executeQuery();
  202.            
  203.             while (rs.next()) {
  204.                 tableModel.addRow(new Object[]{
  205.                     rs.getInt(1)
  206.                     ,rs.getString(2)
  207.                     ,rs.getDouble(3)
  208.                     ,rs.getString(4)
  209.                     ,rs.getInt(5)
  210.                 });
  211.             }
  212.            
  213.             conn.close();
  214.         } catch (Exception e) {
  215.             System.out.println(e.getMessage());
  216.         }
  217.     }
  218. }
  219. //-------methods from insert form--------------------------------------
  220.  
  221.     public static boolean isNumeric(String strNum) {
  222.         if (strNum == null) {
  223.             return false;
  224.         }
  225.         try {
  226.             double d = Double.parseDouble(strNum);
  227.         } catch (NumberFormatException nfe) {
  228.             return false;
  229.         }
  230.         return true;
  231.     }
  232.    
  233.     public Color isNumericColor(String strNum){
  234.         if (strNum == null) {
  235.             return Color.RED;
  236.         }
  237.         try {
  238.             double d = Double.parseDouble(strNum);
  239.         } catch (NumberFormatException nfe) {
  240.             return Color.RED;
  241.         }
  242.         return Color.white;
  243.     }
  244.    
  245.     public Color isEmptyColor(String strNum){
  246.         if (strNum == null || strNum.trim().isEmpty()) {
  247.             return Color.RED;
  248.         } else {
  249.             return Color.white;
  250.         }
  251.     }
  252.    
  253.     public int getCategoryId(String catSelected) {
  254.         int catId = 0;
  255.         int barLoc = catSelected.indexOf("|");
  256.         catId = Integer.parseInt(catSelected.substring(0,barLoc));
  257.         return catId;
  258.     }
  259.  
  260. //-------event methods from insert form--------------------------------------
  261. private void formWindowActivated(java.awt.event.WindowEvent evt) {                                    
  262.         // TODO add your handling code here:
  263.         CrudProductListD21 callCrud = new CrudProductListD21();
  264.         String[] categoryList = callCrud.setCatComboBox();
  265.         for (String string : categoryList) {
  266.             cmbCategory.addItem(string);
  267.         }
  268.     }                                    
  269.  
  270.     private void txtPriceKeyReleased(java.awt.event.KeyEvent evt) {                                    
  271.         // TODO add your handling code here:
  272.         String txtIn = txtPrice.getText();
  273.         txtPrice.setBackground(isNumericColor(txtIn));
  274.     }                                    
  275.  
  276.     private void txtPNameFocusLost(java.awt.event.FocusEvent evt) {                                  
  277.         // TODO add your handling code here:
  278.         String txtIn = txtPName.getText();
  279.         txtPName.setBackground(isEmptyColor(txtIn));
  280.     }                                  
  281.  
  282.     private void txtManufacturerFocusLost(java.awt.event.FocusEvent evt) {                                          
  283.         // TODO add your handling code here:
  284.         String txtIn = txtManufacturer.getText();
  285.         txtManufacturer.setBackground(isEmptyColor(txtIn));
  286.     }                                        
  287.  
  288.     private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {                                      
  289.         // TODO add your handling code here:
  290.         boolean isValid = true;
  291.         if (txtPName.getBackground() == Color.RED
  292.             || txtPrice.getBackground() == Color.RED
  293.             || txtManufacturer.getBackground() == Color.RED) {
  294.             isValid = false;
  295.             JOptionPane.showMessageDialog(this, "One or more of the values is invalid");
  296.         } else {
  297.             String pName = txtPName.getText();
  298.             String pManufacturer = txtManufacturer.getText();
  299.             double pPrice = Double.parseDouble(txtPrice.getText());
  300.             int catId = getCategoryId(cmbCategory.getSelectedItem().toString());
  301.             CrudProductListD21 callCRUD = new CrudProductListD21();
  302.             int rowAffected = callCRUD.addNewRow(pName, pPrice, pManufacturer, catId);
  303.             if (rowAffected == 1) {
  304.                 JOptionPane.showMessageDialog(this, "New Row Added");
  305.             } else {
  306.                 JOptionPane.showMessageDialog(this, "Add row failed");
  307.             }
  308.         }
  309.     }
Advertisement
Add Comment
Please, Sign In to add comment