Guest User

Untitled

a guest
Sep 21st, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.26 KB | None | 0 0
  1. /*
  2.  * @author Timothy White
  3.  * Program: dbManipulatorGUI
  4.  * Purpose: Allows one to interact with a connected database
  5.  */
  6.  
  7. // imports for project
  8. import java.awt.*;
  9. import java.awt.event.*;
  10. import java.sql.*;
  11. import javax.swing.*;
  12. import javax.swing.event.*;
  13.  
  14. public class dbManipulatorGUI extends JFrame implements ActionListener
  15. {
  16.  
  17.     /* Class Wide Variables
  18.      * Relating to GUI & The DB Object
  19.      */
  20.     public static DBAccessObject objDBAccess;
  21.  
  22.     private static boolean
  23.         blnLeftWindowPopulated = false;
  24.  
  25.     private static JButton
  26.         jbtnExecute = new JButton("Execute"),
  27.         jbtnClear = new JButton("Clear"),
  28.         jbtnExit = new JButton("Exit");
  29.  
  30.     private static DefaultListModel<String>
  31.         dlmSQLPanelLeft = new DefaultListModel<String>(),
  32.         dlmSQLPanelRight = new DefaultListModel<String>();
  33.  
  34.     private static JList<String>
  35.         jlstSQLPanelLeft = new JList<String>( dlmSQLPanelLeft ),
  36.         jlstSQLPanelRight = new JList<String>( dlmSQLPanelRight );
  37.  
  38.     private static JTextArea
  39.         jtaInput = new JTextArea(15, 1),
  40.         jtaOutput = new JTextArea(15, 1);
  41.  
  42.     /* Constructor dbManipulatorGUI
  43.      * Sets the functionality of the GUI
  44.      */
  45.     public dbManipulatorGUI()
  46.     {
  47.         super("Timothy White's DB Tool");
  48.         setSize(560, 640);
  49.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  50.  
  51.         JPanel jpnlMain = new JPanel();
  52.         JPanel jpnlNorth = new JPanel();
  53.         JPanel jpnlCenter = new JPanel();
  54.         JPanel jpnlSouth = new JPanel();
  55.  
  56.         jpnlMain.setLayout(new BorderLayout());
  57.         jpnlNorth.setLayout(new GridLayout(1, 2));
  58.         jpnlCenter.setLayout(new GridLayout(2, 1));
  59.         jpnlSouth.setLayout(new GridLayout(1, 3));
  60.  
  61.         jpnlMain.add(jpnlNorth, BorderLayout.NORTH);
  62.         jpnlMain.add(jpnlCenter, BorderLayout.CENTER);
  63.         jpnlMain.add(jpnlSouth, BorderLayout.SOUTH);
  64.  
  65.         jpnlNorth.add(new JScrollPane(jlstSQLPanelLeft));
  66.         jpnlNorth.add(new JScrollPane(jlstSQLPanelRight));
  67.  
  68.         jpnlCenter.add(new JScrollPane(jtaInput));
  69.         jpnlCenter.add(new JScrollPane(jtaOutput));
  70.  
  71.         jlstSQLPanelLeft.addListSelectionListener(new ListBoxListener());
  72.  
  73.         jbtnExecute.addActionListener(this);
  74.         jbtnClear.addActionListener(this);
  75.         jbtnExit.addActionListener(this);
  76.  
  77.         jpnlSouth.add(jbtnExecute);
  78.         jpnlSouth.add(jbtnClear);
  79.         jpnlSouth.add(jbtnExit);
  80.  
  81.         Container ctnObjDBTool = getContentPane();
  82.         ctnObjDBTool.setBackground(Color.lightGray);
  83.         ctnObjDBTool.add(jpnlMain);
  84.  
  85.         setContentPane(ctnObjDBTool);
  86.         setVisible(true);
  87.     }
  88.  
  89.     /* ListBoxListener
  90.      * This handles the upper left list boxes click events.
  91.      * Depending on which DB table is clicked, corresponds to
  92.      * what columns are added to the right list box.
  93.      */
  94.     class ListBoxListener implements ListSelectionListener
  95.     {
  96.         public void valueChanged(ListSelectionEvent e)
  97.         {
  98.             if (!e.getValueIsAdjusting())
  99.             {
  100.                 dlmSQLPanelRight.clear();
  101.                 try
  102.                 {
  103.                     ResultSetMetaData rsmdColumns = objDBAccess.getResultMetaData(jlstSQLPanelLeft.getSelectedValue());
  104.                     for (int iCount = 1; iCount <= rsmdColumns.getColumnCount(); iCount++)  {
  105.                         dlmSQLPanelRight.addElement(rsmdColumns.getColumnLabel(iCount) + " (" + rsmdColumns.getColumnTypeName(iCount) + ")");
  106.                     }
  107.                 }
  108.                 catch (SQLException err)
  109.                 {
  110.                     setOutput(err.getMessage());
  111.                 }
  112.             }
  113.         }
  114.     }
  115.  
  116.     /* clearScreen()
  117.      * Clears all the writable GUI components
  118.      */
  119.     public void clearScreen()
  120.     {
  121.         jtaInput.setText("");
  122.         jtaOutput.setText("");
  123.     }
  124.  
  125.     /* setOutput
  126.      * used for easily appending output to the jtaOutput JTextArea
  127.      */
  128.     public void setOutput(String sMessage)
  129.     {
  130.         jtaOutput.append(sMessage);
  131.     }
  132.  
  133.     /* doExecution()
  134.      * Handles the execution button.
  135.      * Will push the user inputted query
  136.      * and show results in the bottom JTextArea
  137.      * accordingly.
  138.      */
  139.     public void doExecution()
  140.     {
  141.         String sPrepOutput = "";
  142.         try
  143.         {
  144.             // This if is to check if the statement issued is a SELECT
  145.             if(jtaInput.getText().length() >= 6 && jtaInput.getText().substring(0, 6).equalsIgnoreCase("SELECT"))
  146.             {
  147.                 // Attempt to get a result set from the inputted query
  148.                 ResultSet rsSQLselect = objDBAccess.getResultSet(jtaInput.getText());
  149.                 // get the result sets meta data so I can see the column names
  150.                 ResultSetMetaData rsmdSelect = rsSQLselect.getMetaData();
  151.                 // get total column names
  152.                 int iTotalColumns = rsmdSelect.getColumnCount();
  153.  
  154.                 // loop through them and tab them nicely
  155.                 for(int i = 1; i < iTotalColumns + 1; i++)
  156.                 {
  157.                     sPrepOutput += rsmdSelect.getColumnName(i) + "\t";
  158.                 }
  159.  
  160.                 sPrepOutput += "\n";
  161.  
  162.                 // loop through the results and tab them
  163.                 while(rsSQLselect.next())
  164.                 {
  165.                     for(int i = 1; i < iTotalColumns + 1; i++)
  166.                     {
  167.                         sPrepOutput += rsSQLselect.getString(i) + "\t";
  168.                     }
  169.                     sPrepOutput += "\n";
  170.                 }
  171.                 // write all the prepped output to the JTextArea
  172.                 setOutput(sPrepOutput);
  173.  
  174.             }
  175.             // If It's not a select statement, this is executed.
  176.             else
  177.             {
  178.                 // Holds the affected rows from the executed query
  179.                 int iSQLResults = objDBAccess.executeSQL(jtaInput.getText());
  180.  
  181.                 // Populate Left Window in case Table Query is made
  182.                 dlmSQLPanelLeft.clear();
  183.                 populateLeftWindow();
  184.  
  185.                 // Appends output to the JTextArea regarding the results from query made above.
  186.                 setOutput(iSQLResults + " results produced from query " + jtaInput.getText() + "\n");
  187.             }
  188.         }
  189.         catch (SQLException e)
  190.         {
  191.             setOutput("SQL ERROR: " + e.getMessage() + "\n");
  192.         }
  193.         catch (Exception e)
  194.         {
  195.             setOutput("General Error: " + e.getMessage() + "\n");
  196.         }
  197.     }
  198.  
  199.     /* actionPerformed
  200.      * Handles the button clicks associated with the GUI
  201.      */
  202.     public void actionPerformed(java.awt.event.ActionEvent e)
  203.     {
  204.         try
  205.         {
  206.             // cast the source to a jbutton
  207.             JButton jbtnClicked = (JButton) e.getSource();
  208.  
  209.             // depending on the jbutton text decides what happens from here
  210.             if(jbtnClicked.getText().equals("Execute"))
  211.                 doExecution();
  212.  
  213.             else if(jbtnClicked.getText().equals("Clear"))
  214.                 clearScreen();
  215.  
  216.             else
  217.                 System.exit(0);
  218.  
  219.         }
  220.         catch (Exception err)
  221.         {
  222.             setOutput(err.getMessage() + "\n");
  223.         }
  224.     }
  225.  
  226.     /* populateLeftWindow()
  227.      * Populates the upper left list window of the GUI with the database tables
  228.      */
  229.     public static void populateLeftWindow()
  230.     {
  231.         // Try to get the tables from DB
  232.         try
  233.         {
  234.             // try to get a result set
  235.             ResultSet rsDBTables = objDBAccess.getDatabaseTableNames();
  236.  
  237.             // loop through the results and add them to the right window
  238.             while(rsDBTables.next())
  239.             {
  240.                 dlmSQLPanelLeft.addElement(rsDBTables.getString("TABLE_NAME"));
  241.             }
  242.         }
  243.         catch (SQLException e)
  244.         {
  245.             jtaOutput.append(e.getMessage() + "\n");
  246.         }
  247.     }
  248.  
  249.     /* Main for dbManipulatorGUI
  250.      * Instantiates GUI and Attempts to connect the DB
  251.      * Then Populates the Upper Left List with the corresponding tables from the selected DB
  252.      * Then sets the selected Index to 0 to show the tables inside the DB by default.
  253.      */
  254.     public static void main(String[] args)
  255.     {
  256.         try
  257.         {
  258.             objDBAccess = new DBAccessObject("jdbc:mysql://localhost:3306/empdb");
  259.         }
  260.         catch (Exception e)
  261.         {
  262.             System.out.println("Failed to instantiate Database");
  263.         }
  264.  
  265.         dbManipulatorGUI objDbMan = new dbManipulatorGUI();
  266.  
  267.         dbManipulatorGUI.populateLeftWindow();
  268.         jlstSQLPanelLeft.setSelectedIndex(0);
  269.  
  270.     }
  271. }
Add Comment
Please, Sign In to add comment