Advertisement
Skizerzz

JDBC Transactions, Rollbacks, and Commits

May 5th, 2016
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.39 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package a_project;
  7.  
  8. import java.sql.Connection;
  9. import java.sql.DriverManager;
  10. import java.sql.PreparedStatement;
  11. import java.sql.ResultSet;
  12. import java.sql.Date;
  13. import java.util.*;
  14. import java.util.ArrayList;
  15. import java.sql.SQLException;
  16. import java.sql.Timestamp;
  17. import javax.swing.table.DefaultTableModel;
  18. import javax.swing.JOptionPane;
  19. import java.awt.Color;
  20. import java.awt.image.BufferedImage;
  21. import java.awt.Image;
  22. import java.io.*;
  23. import javax.imageio.ImageIO;
  24. import java.net.URL;
  25.  
  26.  
  27.  
  28. /**
  29.  *
  30.  * @author brenn
  31.  */
  32. public class NewJFrame extends javax.swing.JFrame {
  33.  
  34.     /**
  35.      * Creates new form NewJFrame
  36.      */
  37.     public NewJFrame() {
  38.         initComponents();
  39.         fillMenu();
  40.     }
  41.  
  42.     /**
  43.      * This method is called from within the constructor to initialize the form.
  44.      * WARNING: Do NOT modify this code. The content of this method is always
  45.      * regenerated by the Form Editor.
  46.      */
  47.     @SuppressWarnings("unchecked")
  48.     // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  49.     private void initComponents() {
  50.  
  51.         jComboBox1 = new javax.swing.JComboBox<>();
  52.         jTextField1 = new javax.swing.JTextField();
  53.         jButton1 = new javax.swing.JButton();
  54.  
  55.         setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  56.         setBackground(new java.awt.Color(102, 102, 102));
  57.         setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
  58.         setMaximumSize(new java.awt.Dimension(350, 180));
  59.         setMinimumSize(new java.awt.Dimension(350, 180));
  60.         setPreferredSize(new java.awt.Dimension(350, 180));
  61.         setResizable(false);
  62.  
  63.         jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
  64.  
  65.         jButton1.setText("Submit");
  66.         jButton1.addActionListener(new java.awt.event.ActionListener() {
  67.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  68.                 jButton1ActionPerformed(evt);
  69.             }
  70.         });
  71.  
  72.         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  73.         getContentPane().setLayout(layout);
  74.         layout.setHorizontalGroup(
  75.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  76.             .addGroup(layout.createSequentialGroup()
  77.                 .addGap(20, 20, 20)
  78.                 .addComponent(jComboBox1, 0, 167, Short.MAX_VALUE)
  79.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  80.                 .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
  81.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  82.                 .addComponent(jButton1)
  83.                 .addGap(32, 32, 32))
  84.         );
  85.         layout.setVerticalGroup(
  86.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  87.             .addGroup(layout.createSequentialGroup()
  88.                 .addGap(62, 62, 62)
  89.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  90.                     .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  91.                     .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  92.                     .addComponent(jButton1))
  93.                 .addContainerGap(37, Short.MAX_VALUE))
  94.         );
  95.  
  96.         pack();
  97.     }// </editor-fold>                        
  98.  
  99.    
  100.     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
  101.         // TODO add your handling code here:
  102.         Connection con = null;
  103.         PreparedStatement pstmt = null;
  104.         String user = "USERNAME";
  105.         String pass = "PASSWORD";
  106.         String url = "jdbc:db2://localhost:55000/";
  107.         String sql = "";
  108.         Boolean order_more = false;
  109.         String quantityStr = jTextField1.getText();
  110.         int quantity = 0;
  111.         String selected_item = jComboBox1.getSelectedItem().toString();
  112.                
  113.         try
  114.         {
  115.             quantity = Integer.parseInt(quantityStr);
  116.             sql = "SELECT R.INV_QTY_NEEDED * " + quantity + " - I.INV_QTY_ONHAND, I.INV_NAME, I.INV_REORDER_PRICE, I.INV_REORDER_AMT" //CHECKING IF INVENTORY IS AVAILABLE, EMPTY IF ALL AVAILABLE
  117.                     + " FROM RECIPE R"
  118.                     + "     JOIN INVENTORY I"
  119.                     + "         ON R.INV_ID = I.INV_ID"
  120.                     + "     JOIN BAKERY_ITEMS B"
  121.                     + "         ON B.BAKERY_ITEM_ID = R.BAKERY_ITEM_ID"
  122.                     + " WHERE R.INV_QTY_NEEDED * " + quantity + " > I.INV_QTY_ONHAND AND R.BAKERY_ITEM_ID = (SELECT BAKERY_ITEM_ID FROM BAKERY_ITEMS WHERE BAKERY_ITEM_NAME LIKE ('" + selected_item + "') GROUP BY BAKERY_ITEM_ID)";
  123.             con = DriverManager.getConnection(url, user, pass);
  124.             con.setAutoCommit(false);
  125.             //System.out.println(sql);
  126.            
  127.             ResultSet rs = null;
  128.             ArrayList<Integer> needed = new ArrayList<Integer>();
  129.             ArrayList<String> names = new ArrayList<String>();
  130.             ArrayList<Double> prices = new ArrayList<Double>();
  131.             ArrayList<Integer> reOrderAmt = new ArrayList<Integer>();
  132.             pstmt = con.prepareStatement(sql);
  133.             rs = pstmt.executeQuery();
  134.             if(rs != null)
  135.             {
  136.                 int counter = 0;
  137.                 while (rs.next())
  138.                 {
  139.                     needed.add(Integer.parseInt(rs.getString(1)));
  140.                     names.add(rs.getString(2));
  141.                     prices.add(Double.parseDouble(rs.getString(3)));
  142.                     reOrderAmt.add(Integer.parseInt(rs.getString(4)));
  143.                     counter++;
  144.                 }
  145.  
  146.                 if(counter == 0) //There WAS enough inventory available, attempt transaction. -----------------------
  147.                 {
  148.                     java.util.Date date = new java.util.Date();
  149.                     java.sql.Date curDate = new java.sql.Date(date.getTime());
  150.                     sql = "INSERT INTO ORDERS (ORDER_DATE, BAKERY_ITEM_ID, ORDER_QUANTITY) "
  151.                             + "VALUES (DATE("+curDate+"), (SELECT BAKERY_ITEM_ID FROM BAKERY_ITEMS WHERE BAKERY_ITEM_NAME LIKE('"+selected_item+"') GROUP BY BAKERY_ITEM_ID), "+quantity+")"
  152.                         ;//+ " UNION "
  153.  
  154.                     pstmt = con.prepareStatement(sql);
  155.                     pstmt.executeUpdate();
  156.                    
  157.                     java.sql.Timestamp myTStamp = new java.sql.Timestamp(System.currentTimeMillis());
  158.                    
  159.                     sql = "INSERT INTO TRANSACTION_JOURNAL (JOURNAL_DESCRIPTION, JOURNAL_AMOUNT, JOURNAL_TIME)"
  160.                                 + " VALUES "
  161.                             + "('SUCCESSFUL ORDER OF ("+selected_item+") x("+quantity+")', "
  162.                             + quantity + " * (SELECT BAKERY_ITEM_PRICE FROM BAKERY_ITEMS WHERE BAKERY_ITEM_NAME LIKE('"+selected_item+"') GROUP BY BAKERY_ITEM_PRICE), "
  163.                              + "'" + myTStamp + "')";
  164.                    
  165.                     pstmt = con.prepareStatement(sql);
  166.                     pstmt.executeUpdate();
  167.                     jTextField1.setText("");
  168.                     JOptionPane.showMessageDialog(null, "Successfully ordered " + selected_item + " x " + quantity + ".", "Notice", JOptionPane.WARNING_MESSAGE);
  169.                    
  170.                     con.commit();
  171.                 }
  172.                 else             //There WASN'T enough inventory available, order more inventory. ---------------------
  173.                 {
  174.                     java.sql.Timestamp myTStamp = new java.sql.Timestamp(System.currentTimeMillis());
  175.                     int orderCount = 0;
  176.                     double num = 0.0;
  177.                    
  178.                     for(int i = 0; i < needed.size(); i++)
  179.                     {
  180.                         orderCount = (int)(needed.get(i) / reOrderAmt.get(i));
  181.                         num = orderCount * prices.get(i);
  182.                         num = -num;
  183.                        
  184.                         sql = "INSERT INTO TRANSACTION_JOURNAL (JOURNAL_DESCRIPTION, JOURNAL_AMOUNT, JOURNAL_TIME)"
  185.                                 + " VALUES "
  186.                                 + "('ORDERING INVENTORY ITEM " + names.get(i) + " WITH A QUANTITY OF " + orderCount + "', "
  187.                                 + num + ", "//"-" + needed.get(i) * prices.get(i) + ", "
  188.                                 + "'" + myTStamp + "')";
  189.                         System.out.println("Entry " + (i + 1) + " out of " + needed.size());
  190.                         pstmt = con.prepareStatement(sql);
  191.                         pstmt.executeUpdate();
  192.                     }
  193.                    
  194.                     sql = "SELECT SUM(JOURNAL_AMOUNT)"
  195.                             + " FROM TRANSACTION_JOURNAL";
  196.                    
  197.                     pstmt = con.prepareStatement(sql);
  198.                     rs = pstmt.executeQuery();
  199.                    
  200.                     if(rs != null)
  201.                     {
  202.                         num = 0.0;
  203.                         rs.next();
  204.                         num = Double.parseDouble(rs.getString(1));
  205.                         if(num < 0)
  206.                         {
  207.                             jTextField1.setText("");
  208.                             JOptionPane.showMessageDialog(null, "Order failed: Money don't grow on trees (AKA Insufficient Funds).", "Notice", JOptionPane.WARNING_MESSAGE);
  209.                             con.rollback();
  210.                         }
  211.                         else
  212.                         {
  213.                             jTextField1.setText("");
  214.                             JOptionPane.showMessageDialog(null, "Insufficient inventory, more inventory has been ordered.", "Notice", JOptionPane.WARNING_MESSAGE);
  215.                             con.commit();
  216.                         }
  217.                     }
  218.                 }
  219.             }
  220.         }
  221.         catch(Exception ex)
  222.         {
  223.             jTextField1.setText("");
  224.             JOptionPane.showMessageDialog(null, "Please enter a number value.", "Notice", JOptionPane.WARNING_MESSAGE);
  225.         }
  226.        
  227.         try
  228.         {
  229.             if(con != null)
  230.             {
  231.                 con.close();
  232.             }
  233.         }
  234.         catch (Exception ex)
  235.         {
  236.             ex.printStackTrace();
  237.         }
  238.     }                                        
  239.  
  240.     /**
  241.      * @param args the command line arguments
  242.      */
  243.     public static void main(String args[]) {
  244.         /* Set the Nimbus look and feel */
  245.         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  246.         /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  247.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  248.          */
  249.         try {
  250.             for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  251.                 if ("Nimbus".equals(info.getName())) {
  252.                     javax.swing.UIManager.setLookAndFeel(info.getClassName());
  253.                     break;
  254.                 }
  255.             }
  256.         } catch (ClassNotFoundException ex) {
  257.             java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  258.         } catch (InstantiationException ex) {
  259.             java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  260.         } catch (IllegalAccessException ex) {
  261.             java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  262.         } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  263.             java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  264.         }
  265.         //</editor-fold>
  266.  
  267.         /* Create and display the form */
  268.         java.awt.EventQueue.invokeLater(new Runnable() {
  269.             public void run() {
  270.                 new NewJFrame().setVisible(true);
  271.             }
  272.         });
  273.     }
  274.    
  275.     private void fillMenu()
  276.     {
  277.         Connection con = null;
  278.         PreparedStatement pstmt = null;
  279.         String user = "USERNAME";
  280.         String pass = "PASSWORD";
  281.         String url = "jdbc:db2://localhost:55000/";
  282.         String sql = "";
  283.        
  284.         try
  285.         {
  286.             Class.forName("com.ibm.db2.jcc.DB2Driver");
  287.         }
  288.         catch (Exception ex)
  289.         {
  290.             ex.printStackTrace();
  291.         }
  292.        
  293.         try
  294.         {
  295.             con = DriverManager.getConnection(url, user, pass);
  296.         }
  297.         catch (Exception ex)
  298.         {
  299.             ex.printStackTrace();
  300.             return;
  301.         }
  302.        
  303.         sql = "SELECT BAKERY_ITEM_NAME"
  304.                 + " FROM BAKERY_ITEMS";
  305.        
  306.         ResultSet rs = null;
  307.         try
  308.         {
  309.             pstmt = con.prepareStatement(sql);
  310.             rs = pstmt.executeQuery();
  311.             if(rs != null)
  312.             {
  313.                 String item_name = "";
  314.                 ArrayList<String> items = new ArrayList<String>();
  315.                 int counter = 0;
  316.                 while (rs.next()){
  317.                     item_name = rs.getString(1);
  318.                     items.add(item_name);
  319.                     counter++;
  320.                 }
  321.                 jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(items.toArray()));
  322.             }
  323.         }
  324.         catch (Exception ex)
  325.         {
  326.             ex.printStackTrace();
  327.         }
  328.        
  329.         try
  330.         {
  331.             con.close();
  332.         }
  333.         catch (Exception ex)
  334.         {
  335.             ex.printStackTrace();
  336.         }
  337.     }
  338.  
  339.     // Variables declaration - do not modify                    
  340.     private javax.swing.JButton jButton1;
  341.     private javax.swing.JComboBox<String> jComboBox1;
  342.     private javax.swing.JTextField jTextField1;
  343.     // End of variables declaration                  
  344. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement