Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.92 KB | None | 0 0
  1. package project3;
  2.  
  3. // Display the results of queries against the bikes table in the bikedb database.
  4. import java.awt.BorderLayout;
  5.  
  6. import javax.swing.JComboBox;
  7. import java.awt.Color;
  8. import java.awt.event.ActionListener;
  9. import java.awt.event.ActionEvent;
  10. import java.awt.event.WindowAdapter;
  11. import java.awt.event.WindowEvent;
  12. import java.sql.Connection;
  13. import java.sql.ResultSet;
  14. import java.sql.SQLException;
  15. import java.sql.Statement;
  16.  
  17. import javax.swing.JFrame;
  18. import javax.swing.JLabel;
  19. import javax.swing.JTextArea;
  20. import javax.swing.JTextField;
  21. import javax.swing.JScrollPane;
  22. import javax.swing.ScrollPaneConstants;
  23.  
  24. import javax.sql.DataSource;
  25. import com.mysql.cj.jdbc.MysqlDataSource;
  26.  
  27. import javax.swing.JTable;
  28. import javax.swing.JOptionPane;
  29. import javax.swing.JButton;
  30. import javax.swing.Box;
  31.  
  32.  
  33. public class DisplayQueryResults extends JFrame
  34. {
  35.    // default query retrieves all data from bikes table
  36.    static final String DEFAULT_QUERY = "SELECT * FROM bikes";
  37.    
  38.    
  39.    
  40.    
  41.    private Connection connection;
  42.    private Statement statement;
  43.    private ResultSetTableModel tableModel;
  44.    private JTextArea queryArea;
  45.    
  46.    // create ResultSetTableModel and GUI
  47.    public DisplayQueryResults()
  48.    {  
  49.       super( "Displaying Query Results" );
  50.        
  51.       boolean isConnected;
  52.       // create ResultSetTableModel and display database table
  53.       try
  54.       {
  55.          
  56.          // create TableModel for results of query SELECT * FROM bikes
  57.           tableModel = new ResultSetTableModel( DEFAULT_QUERY);
  58.  
  59.          
  60.          // set up JTextArea in which user types queries
  61.         //  queryArea = new JTextArea( 3, 100);
  62.          queryArea = new JTextArea( DEFAULT_QUERY, 3, 100 );
  63.          queryArea.setWrapStyleWord( true );
  64.          queryArea.setLineWrap( true );
  65.          
  66.  
  67.          
  68.          JScrollPane scrollPane = new JScrollPane( queryArea,
  69.             ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
  70.             ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
  71.          
  72.          // set up JButton for submitting queries
  73.          JButton submitButton = new JButton( " Execute SQL Command " );
  74.          submitButton.setBackground(Color.GREEN);
  75.          submitButton.setForeground(Color.BLUE);
  76.          
  77.          JButton clearButton = new JButton( " Clear SQL Command " );
  78.          clearButton.setBackground(Color.WHITE);
  79.          clearButton.setForeground(Color.RED);
  80.          
  81.          JButton connectButton = new JButton( " Connect to Database " );
  82.          connectButton.setBackground(Color.BLUE);
  83.          connectButton.setForeground(Color.YELLOW);
  84.          
  85.          String[] connection1 = { "jdbc:mysql://127.0.0.1:3312/project3"};
  86.          String[] connection2 = { "com.mysql.cj.jdbc.MysqlDataSource"};
  87.          
  88.          
  89.          JComboBox<String> connectionMenu = new JComboBox<String>(connection1);
  90.          JLabel cMenu1 = new JLabel("JDBC Driver");
  91.          JComboBox<String> connectionMenu2 = new JComboBox<String>(connection2);
  92.          JLabel cMenu2 = new JLabel("Database Username");
  93.          
  94.          
  95.  
  96.          JTextField userField = new JTextField(16);
  97.          JTextField passField = new JTextField(16);
  98.          
  99.          
  100.          // create Box to manage placement of queryArea and
  101.          // submitButton in GUI
  102.          Box box = Box.createHorizontalBox();
  103.          
  104.          box.add( scrollPane );
  105.          box.add( submitButton );
  106.          box.add( clearButton );
  107.          box.add( connectButton );
  108.          box.add(cMenu1);
  109.          box.add(connectionMenu);
  110.          box.add(cMenu2);
  111.          box.add(connectionMenu2);
  112.          
  113.        
  114.          Box box2 = Box.createHorizontalBox();
  115.          box2.add(clearButton);
  116.          
  117.          //THIS IS WHERE I ADD MORE BUTTONS
  118.  
  119.          // create JTable delegate for tableModel
  120.          JTable resultTable = new JTable( tableModel );
  121.          
  122.          // place GUI components on content pane
  123.          add( box, BorderLayout.NORTH );
  124.          
  125.          add(queryArea, BorderLayout.EAST);
  126.          add( new JScrollPane( resultTable ), BorderLayout.SOUTH );
  127.          
  128.          
  129.          add(box2, BorderLayout.WEST);
  130.          box2.add(new JLabel("Username"));
  131.          box2.add(userField, BorderLayout.WEST);
  132.          box2.add(new JLabel("Password"));
  133.          box2.add(passField, BorderLayout.WEST);
  134.          
  135.          //box2.add(new JTextField(16), BorderLayout.WEST); <- not sure if I need this
  136.          
  137.  
  138.        MysqlDataSource dataSource = null;
  139.          connectButton.addActionListener(
  140.             new ActionListener()
  141.             {
  142.                     // pass query to table model
  143.                public void actionPerformed( ActionEvent event )
  144.                {
  145.                        // perform a new query
  146.                 try
  147.                 {
  148.  
  149.                     dataSource = new MysqlDataSource();
  150.                     dataSource.setURL(connectionMenu2.getItemAt(0).toString());
  151.                     dataSource.setUser(userField.getText());
  152.                     dataSource.setPassword(passField.getText());
  153.  
  154.                     Connection connection = dataSource.getConnection();
  155.  
  156.  
  157.            
  158.                     // create Statement to query database
  159.                     //statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
  160.  
  161.                    
  162.                 }
  163.                 catch ( SQLException sqlException )
  164.                 {
  165.                    sqlException.printStackTrace();
  166.                    System.exit( 1 );
  167.                 }
  168.                }
  169.             });
  170.  
  171.          
  172.          clearButton.addActionListener(
  173.                 new ActionListener()
  174.                  {
  175.                          // pass query to table model
  176.                     public void actionPerformed( ActionEvent event )
  177.                     {
  178.                             resultTable.setVisible(false);
  179.                     }
  180.                  });
  181.          
  182.          
  183.          // create event listener for submitButton
  184.          submitButton.addActionListener(
  185.          
  186.             new ActionListener()
  187.             {
  188.                // pass query to table model
  189.                public void actionPerformed( ActionEvent event )
  190.                {
  191.                   // perform a new query
  192.                   try
  193.                   {
  194.                    
  195.                  resultTable.setVisible(true);
  196.                  if (queryArea.getText().toUpperCase().contains("SELECT")) {
  197.                    tableModel.setQuery( queryArea.getText() );
  198.                    resultTable.setModel(tableModel);
  199.                  
  200.                  }
  201.                  else {
  202.                      tableModel.setUpdate(queryArea.getText());
  203.                    
  204.                    }
  205.              
  206.                          
  207.                      //
  208.                      
  209.                   } // end try
  210.                   catch ( SQLException sqlException )
  211.                   {
  212.                      JOptionPane.showMessageDialog( null,
  213.                         sqlException.getMessage(), "Database error",
  214.                         JOptionPane.ERROR_MESSAGE );
  215.                      
  216.                      // try to recover from invalid user query
  217.                      // by executing default query
  218.                      try
  219.                      {
  220.                         tableModel.setQuery( DEFAULT_QUERY );
  221.                         queryArea.setText( DEFAULT_QUERY );
  222.                      } // end try
  223.                      catch ( SQLException sqlException2 )
  224.                      {
  225.                         JOptionPane.showMessageDialog( null,
  226.                            sqlException2.getMessage(), "Database error",
  227.                            JOptionPane.ERROR_MESSAGE );
  228.          
  229.                         // ensure database connection is closed
  230.                         tableModel.disconnectFromDatabase();
  231.                        
  232.                         System.exit( 1 ); // terminate application
  233.                      } // end inner catch                  
  234.                   } // end outer catch
  235.                } // end actionPerformed
  236.             }  // end ActionListener inner class          
  237.          ); // end call to addActionListener
  238.  
  239.          setSize( 600, 300 ); // set window size
  240.          setVisible( true ); // display window  
  241.       } // end try
  242.       catch ( ClassNotFoundException classNotFound )
  243.       {
  244.          JOptionPane.showMessageDialog( null,
  245.             "MySQL driver not found", "Driver not found",
  246.             JOptionPane.ERROR_MESSAGE );
  247.          isConnected = false;
  248.          System.exit( 1 ); // terminate application
  249.       } // end catch
  250.       catch ( SQLException sqlException )
  251.       {
  252.          JOptionPane.showMessageDialog( null, sqlException.getMessage(),
  253.             "Database error", JOptionPane.ERROR_MESSAGE );
  254.                
  255.          // ensure database connection is closed
  256.          tableModel.disconnectFromDatabase();
  257.          isConnected = false;
  258.          System.exit( 1 );   // terminate application
  259.       } // end catch
  260.      
  261.       // dispose of window when user quits application (this overrides
  262.       // the default of HIDE_ON_CLOSE)
  263.       setDefaultCloseOperation( DISPOSE_ON_CLOSE );
  264.      
  265.       // ensure database connection is closed when user quits application
  266.       addWindowListener(new WindowAdapter()
  267.          {
  268.             // disconnect from database and exit when window has closed
  269.             public void windowClosed( WindowEvent event )
  270.             {
  271.                tableModel.disconnectFromDatabase();
  272.                
  273.                System.exit( 0 );
  274.             } // end method windowClosed
  275.          } // end WindowAdapter inner class
  276.       ); // end call to addWindowListener
  277.    } // end DisplayQueryResults constructor
  278.    
  279.    // execute application
  280.    public static void main( String args[] )
  281.    {
  282.       new DisplayQueryResults();      
  283.    } // end main
  284. } // end class DisplayQueryResults
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement