Page 1 of 3 123 LastLast
Results 1 to 20 of 48
  1. #1
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default finishing up a DB/Java exercise

    so i feel like im almost there, just not understanding the final steps, could someone let me know what i need to do to finish this program up? also as a side note, how do i post my code here WITH line numbers to make it easy for you guys?

    this program primarily i worked from the
    private void stockInfoJButtonActionPerformed( ActionEvent event ) line onward, and im having trouble understand what i need to do to get it finished up. i think im ok up until the "computetotalvalue method, but im starting to not understand exactly what i should be doing in that method. right now when i compile i get a "missing return statement", but there are probably additional issues as well. the DB is called "stockInformation" and contains stockName, stockSymbol, shares, and price fields, i am trying to access those, and also show an additional field in the java program that calculates the # of shares times the price and displays the total.....

    Java Code:
    // Exercise 26.11: StockPortfolio.java
    // Displays a client's stock portfolio.
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.text.*;
    import javax.swing.*;
    
    public class StockPortfolio extends JFrame
    {
       // JLabels for prompt
       private JLabel prompt1JLabel;
       private JLabel prompt2JLabel; 
    
       // JComboBox for stock names
       private JComboBox stockNamesJComboBox;
    
       // JButton for stock information
       private JButton stockInfoJButton;
    
       // JPanel for displaying stock information
       private JPanel stockInfoJPanel;
    
       // JLabel and JTextField for stock name
       private JLabel stockNameJLabel; 
       private JTextField stockNameJTextField;
    
       // JLabel and JTextField for stock symbol
       private JLabel stockSymbolJLabel;
       private JTextField stockSymbolJTextField;
    
       // JLabel and JTextField for number of shares
       private JLabel sharesJLabel; 
       private JTextField sharesJTextField;
    
       // JLabel and JTextField for price of shares
       private JLabel priceJLabel;
       private JTextField priceJTextField;
    
       // JLabel and JTextField for total value
       private JLabel totalJLabel;
       private JTextField totalJTextField;
    
       // instance variables for database processing
       private Connection myConnection;
       private Statement myStatement;
       private ResultSet myResultSet;
    
       // constructor
       public StockPortfolio( String databaseDriver, String databaseURL )
       {
    	   // establish a connection to db
    	   try
    	   {
    		   Class.forName ( databaseDriver );
    		   
    		   // connect to a database
    		   myConnection =
    		   	DriverManager.getConnection (databaseURL );
    		   	
    		   	// create Statement for executing SQL
    		   	myStatement = myConnection.createStatement();
    	   }
    	   catch ( SQLException exception )
    	   {
    		   exception.printStackTrace();
    	   }
    	   catch ( ClassNotFoundException exception )
    	   {
    		   exception.printStackTrace();
    	   }
    	   
          createUserInterface(); // set up GUI
    
       } // end constructor
    
       // create and position GUI components; register event handlers
       private void createUserInterface()
       {
          // get content pane for attaching GUI components
          Container contentPane = getContentPane();
          
          // enable explicit positioning of GUI components
          contentPane.setLayout( null );
    
          // set up prompt1JLlabel
          prompt1JLabel = new JLabel();
          prompt1JLabel.setBounds( 8, 16, 350, 16 );
          prompt1JLabel.setText( "Select the name of " +
             "the stock for which you want " );
          contentPane.add( prompt1JLabel );
    
          // set up prompt2JLabel
          prompt2JLabel = new JLabel();
          prompt2JLabel.setBounds( 8, 32, 350, 16 );
          prompt2JLabel.setText( "information, and then " +
             "press the Stock Information button." );
          contentPane.add( prompt2JLabel );
          
          // set up stockNamesJComboBox 
          stockNamesJComboBox = new JComboBox();
          stockNamesJComboBox.setBounds( 76, 65, 200, 26 );
          stockNamesJComboBox.addItem( "" );
          contentPane.add( stockNamesJComboBox );
          
          // load stock names into stockNamesJComboBox
          loadStockNames();
    
          // set up stockInfoJButton
          stockInfoJButton = new JButton();
          stockInfoJButton.setBounds( 100, 100, 150, 23 );
          stockInfoJButton.setText( "Stock Information" );
          contentPane.add( stockInfoJButton );
          stockInfoJButton.addActionListener(
    
             new ActionListener()  // anonymous inner class
             {
                // event handler called when stockInfoJButton is clicked
                public void actionPerformed( ActionEvent event )
                {
                   stockInfoJButtonActionPerformed( event );
                }
    
             } // end anonymous inner class
    
          ); // end addActionLstener
    
          // set up stockInfoJPanel
          stockInfoJPanel = new JPanel();
          stockInfoJPanel.setBounds( 18, 145, 300, 192 );
          stockInfoJPanel.setLayout( null );
          stockInfoJPanel.setBorder( BorderFactory.createTitledBorder( 
             BorderFactory.createEtchedBorder(), "Stock Info" ) );
          contentPane.add( stockInfoJPanel );
    
          // set up stockNameJLabel
          stockNameJLabel = new JLabel();
          stockNameJLabel.setBounds( 8, 24, 150, 23 );
          stockNameJLabel.setText( "Stock name:" );
          stockInfoJPanel.add( stockNameJLabel );
    
          // set up stockNameJTextField
          stockNameJTextField = new JTextField();
          stockNameJTextField.setBounds( 158, 24, 125, 24 );
          stockNameJTextField.setEditable( false );
          stockNameJTextField.setBorder( 
             BorderFactory.createLoweredBevelBorder() );
          stockNameJTextField.setHorizontalAlignment( 
             JTextField.CENTER );
          stockInfoJPanel.add( stockNameJTextField );
    
          // set up stockSymbolJLabel
          stockSymbolJLabel = new JLabel();
          stockSymbolJLabel.setBounds( 8, 56, 150, 23 );
          stockSymbolJLabel.setText( "Stock symbol:" );
          stockInfoJPanel.add( stockSymbolJLabel );
    
          // set up stockSymbolJTextField
          stockSymbolJTextField = new JTextField();
          stockSymbolJTextField.setBounds( 158, 56, 125, 24 );
          stockSymbolJTextField.setEditable( false );
          stockSymbolJTextField.setBorder( 
             BorderFactory.createLoweredBevelBorder() );
          stockSymbolJTextField.setHorizontalAlignment( 
             JTextField.CENTER );
          stockInfoJPanel.add( stockSymbolJTextField );
    
          // set up sharesJLabel
          sharesJLabel = new JLabel();
          sharesJLabel.setBounds( 8, 88, 150, 23 );
          sharesJLabel.setText( "Number of shares:" );
          stockInfoJPanel.add( sharesJLabel );
    
          // set up sharesJTextField
          sharesJTextField = new JTextField();
          sharesJTextField.setBounds( 158, 88, 125, 24 );
          sharesJTextField.setEditable( false );
          sharesJTextField.setBorder( 
             BorderFactory.createLoweredBevelBorder() );
          sharesJTextField.setHorizontalAlignment( JTextField.CENTER );
          stockInfoJPanel.add( sharesJTextField );
    
          // set up priceJLabel
          priceJLabel = new JLabel();
          priceJLabel.setBounds( 8, 120, 150, 23 );
          priceJLabel.setText( "Price per share:" );
          stockInfoJPanel.add( priceJLabel );
    
          // set up priceJTextField
          priceJTextField = new JTextField();
          priceJTextField.setBounds( 158, 120, 125, 24 );
          priceJTextField.setEditable( false );
          priceJTextField.setBorder( 
             BorderFactory.createLoweredBevelBorder() );
          priceJTextField.setHorizontalAlignment( JTextField.CENTER );
          stockInfoJPanel.add( priceJTextField );
    
          // set up totalJLabel
          totalJLabel = new JLabel();
          totalJLabel.setBounds( 8, 152, 150, 23 );
          totalJLabel.setText( "Total value:" );
          stockInfoJPanel.add( totalJLabel );
    
          // set up totalJTextField
          totalJTextField = new JTextField();
          totalJTextField.setBounds( 158, 152, 125, 24 );
          totalJTextField.setEditable( false );
          totalJTextField.setBorder( 
             BorderFactory.createLoweredBevelBorder() );
          totalJTextField.setHorizontalAlignment( JTextField.CENTER );
          stockInfoJPanel.add( totalJTextField );
    
          // ensure database connection is closed 
          // when user quits application
          addWindowListener(
    
             new WindowAdapter()  // anonymous inner class
             {
                public void windowClosing( WindowEvent event )
                {
                   frameWindowClosing( event );
                }
    
             } // end anonymous inner class
    
          ); // end addWindowListener
    
          // set properties of application's window
          setTitle( "Stock Portfolio" ); // set title bar string
          setSize( 350, 380 );           // set window size
          setVisible( true );            // display window
    
       } // end method createUserInterface
    
       // load stock names into stockNamesJComboBox
       private void loadStockNames()
       {
          // add stock names in database to stockNamesJComboBox
          try
          {
    	      myResultSet = myStatement.executeQuery(
    	      	"SELECT stockNames FROM stockInformation" );
    	      
    	      // add stockNames to stockNamesJComboBox
    	      while ( myResultSet.next() )
    	      {
    		      stockNamesJComboBox.addItem(
    		      	myResultSet.getString ( "stockNames" ) );
    		  }
    		  
    		  myResultSet.close(); // close myResultSet
    		  
    	  }// end try
    	  
    	  catch ( SQLException exception)
    	  {
    		  exception.printStackTrace();
    	  }
          
       } // end method loadStockNames
    
       // user clicked stockInfoJButton
       private void stockInfoJButtonActionPerformed( ActionEvent event )
       {
    	   // get selected stock
    	  String stockName = 
    	  	( String ) stockNamesJComboBox.getSelectedItem(); 
    	  	
    	  	//display stock data
    	  	displayStockData ( stockName );
    	  	
    	} // end method stockInfoJButtonActionPerformed
    	
    	//display stock information
    	private void displayStockData ( String stockName )
    	{
    		//display stock name, stock symbol, shares and price
    		try
    		{
    			//get stock name, stock symbol and shares
    			myResultSet = myStatement.executeQuery( "SELECT stockSymbol,"
    				+ " shares, price FROM stockInformation WHERE " +
    				"stockName = " + ( stockName ) );
    			
    			// non empty result
    			if (myResultSet.next () )
    			{
    				stockNameJTextField.setText(
    					myResultSet.getString( "stockName" ) );
    				stockSymbolJTextField.setText(
    					myResultSet.getString( "stockSymbol" ) );
    				sharesJTextField.setText(
    					myResultSet.getString( "shares" ) );
    				priceJTextField.setText(	
    					myResultSet.getString( "price" ) );
    			}
    			
    			myResultSet.close(); // close myResultSet
    			
    			
    			
    		}
    		catch ( SQLException exception )
          	{
             	exception.printStackTrace();
          	}
    	}// end method display stock data
    	
    	// calculate total value
    	private String computeTotalValue( int shares, double price )
    	{
    		try
    		{
    			
    		//get shares and price
    		shares = myResultSet.getInt( "shares" );
    		price = myResultSet.getDouble( "price" );
    
    		
    		// define display format
    		DecimalFormat dollars = new DecimalFormat( "$0.00" );
    
    		return dollars.format( shares * price );
    		
    		}
    		catch ( SQLException exception )
          	{
             	exception.printStackTrace();
          	}
    		
    
    	} // end method computeTotalValue
    
       // user close window
       private void frameWindowClosing( WindowEvent event )
       {
          // close myStatement and database connection
          try
          {
             myStatement.close();
             myConnection.close();
          }
          catch ( SQLException sqlException )
          {
             sqlException.printStackTrace();
          }
          finally
          {
             System.exit( 0 );
          }
          
       }  // end method frameWindowClosing
    	
       // method main
       public static void main( String[] args )
       {
          // check command-line arguments
          if ( args.length == 2 )
          {
             // get command-line arguments
             String databaseDriver = args[ 0 ];
             String databaseURL = args[ 1 ];
    
             // create new StockPortfolio
             StockPortfolio application = 
                new StockPortfolio( databaseDriver, databaseURL );
          }
          else
          {
             System.out.println( "Usage: java StockPortfolio " + 
                "databaseDriver databaseURL" );
          }
    
       } // end method main
    
    } // end class StockPortfolio
    im guessing im starting to go wrong around line 310, but this is my first week with DB's so basic explanations are beneficial!

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    Java Code:
    // calculate total value
    private String computeTotalValue( int shares, double price )
    {
        try
        {
    			
            //get shares and price
            shares = myResultSet.getInt( "shares" );
            price = myResultSet.getDouble( "price" );
    
    		
            // define display format
            DecimalFormat dollars = new DecimalFormat( "$0.00" );
    
            return dollars.format( shares * price );
    		
        }
        catch ( SQLException exception )
        {
            exception.printStackTrace();
        }
    } // end method computeTotalValue

    You get the "missing return statement" because you have said that this method returns a String and the compiler insists that it will return a string under every normal circumstance. So, basically, if there is an sql exception (that's considered normal because you catch it) you print a stack trace but you don't return a string. And that's what the compiler is complaining about.

    What do you intend to happen if there is an exception? Probably answering that will tell you what (if any) string should be returned.

    --------------------------

    And, generally, people find line numbers make code hard to read and impossible to cut-n-paste.

  3. #3
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    i tried adding an additional statement like:

    totalNameJTextField.setText( myResultSet.getString( "dollars" ) );

    but that cause an additional error, and i really think thats not what i need exactly. but somehow i do need to make the product;
    Java Code:
     return dollars.format( shares * price );
    show up in the JTextBox, right?

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    The "missing return statement" has nothing to do with what is displayed in the text box. It is entirely about ensuring that the computeTotalValue() returns a string as it is declared to do.

    At the moment that method does not return a string if an exception occurs. You will get the "missing return statement" message until you change the code so that the method does return a string.

  5. #5
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    ok, bear with me, im not real knowledgeable with the try/catch things. so there is no return statement in the catch. i understand that now. so i now have 3 questions, haha.

    1. in this particular situation....do i NEED to use try/catch anyway?

    2. should i return the same return string in the catch method that i do in the try method?

    3. should i return some sort of error message in the catch block?

  6. #6
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    well scratch #1, because i just tried removing the try and catch and got an error about uncaught exceptions, so i obviously need the try/catch....haha.

    tried #2 and got an error "cannot find symbol" on the >dollars.format line in the catch method.

    tried #3 JOptionPane.showMessageDialog and still said missing return statement.

    also tried just "return;" but that obviously did work either.

    i have put in the appropriate effort, can someone look at this closely and tell me exactly what im not understanding? i have tried to reference previous projects i have done, but all the methods that i have worked on previously are type "void" so the catch block hasn't had to return anything. i guess im lost on this.

  7. #7
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    ok, bear with me, im not real knowledgeable with the try/catch things

    No problem. Understanding the try/catch is key, take your time. For a general discussion there are pages in the Exceptions section of Oracle's Tutorial that might help.

    The bottom line here is that if anything nasty happens in these two lines

    Java Code:
    shares = myResultSet.getInt( "shares" );
    price = myResultSet.getDouble( "price" );

    then you will end up in the "catch" part of the code. (And - to belabour the point - the compiler is insisting that, even then, you must return a string.) The API docs for getInt() describe the sort of thing that will lead to an exception: "the columnLabel is not valid; ... a database access error occurs or this method is called on a closed result set". The first and last cause (probably) represent programming errors you make, but the middle one is something not really under your control.

    1. in this particular situation....do i NEED to use try/catch anyway?
    2. should i return the same return string in the catch method that i do in the try method?
    3. should i return some sort of error message in the catch block?

    These are good questions. (and the right ones to be asking). I wish there were easy answers! Number 2 *is* easy: you can't return the string representing the product because it is precisely in creating that string that the exception occurs.

    Number 3 is almost as easy - you should probably not return an error message because if you do it will end up being displayed in the text field. This is tacky at best (the user won't know what's going on). More likely it will lead to problems later on if your program uses the value in the text field.

    But do you need to use try/catch? That's why I asked before "What do you intend to happen if there is an exception?"

    As described in the Tutorial I linked to above, there is an option. You can write:

    Java Code:
        /**
         * Returns the total value as a formatted string.
         * @throws SQLException if anything goes wrong
         */
    private String computeTotalValue( int shares, double price ) throws SQLException
    {
        //get shares and price
        shares = myResultSet.getInt( "shares" );
        price = myResultSet.getDouble( "price" );
    
        // define display format
        DecimalFormat dollars = new DecimalFormat( "$0.00" );
    
        return dollars.format( shares * price );
    } // end method computeTotalValue

    In this case an exception can still happen but it will be "thrown" to whoever calls this method. In other words whoever calls this method (it isn't part of the code you've posted - you probably haven't written that bit yet) will have to do so within a try/catch block.

    ------------------------------

    If the focus of the exercise is on getting and displaying information from the database this approach may be acceptable. (As noted above the cause of the exception is most likely a "database error", whatever that means. You may feel your program knows nothing and can do nothing about it.) But you should realise that the error handling is not very robust.

    For instance in the stockInfoJButton click handler you already have a catch block that reports the error but does nothing else. Think about what will actually happen in the event of a random database error. The user will click the button, the error happens and a message will be printed to the console (which the user won't see) instead of the GUI being updated. The user will then cry: "I clicked the button but nothing happened!"

    I would say this is completely accceptable in a database exercise where the focus is not on error handling. But - to repeat - you should recognise that in a more robust program some error dialog box would appear and the program gracefully close down (or take some remedial action).

    ------------------------------

    So, the bottom line: in a real program where lives (or at least livelihoods) are on the line you would do something about database failure. But in an exercise you may be prepared to let methods "throw" the exceptions to whatever called them, and button handlers report the error message to the console but otherwise do nothing.

    [EDIT] corrected critical bit of code
    Last edited by pbrockway2; 12-11-2010 at 09:32 PM.

  8. #8
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    Sorry: took ages to compose my post, so missed the post above it.

  9. #9
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    thank you for your detailed post. i have read through it twice now. im glad i at least posed the appropriate questions, so that it appears that im putting in effort here, and not fishing for answers (although ultimately i need to find the answer to my issue).

    so i read it as, in the real world i would/will need more robust error handling, however in this exercise, where the focus is on how connecting to databases work, and not about error handling, it is less crucial.

    so i have tried to remove the try and the catch block and just leave the method itself, however, i get 2 errors stating "unreported excepton java.sql.SQLException; must be caught or declared to be thrown."

    then it points to the two lines we have discussed....
    Java Code:
        shares = myResultSet.getInt( "shares" );
        price = myResultSet.getDouble( "price" );
    so is a try/catch statement a MUST? how do i get past this?

  10. #10
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    I corrected my post to add a critical part to the method:

    Java Code:
    private String computeTotalValue( int shares, double price ) [b]throws SQLException[/b]
    {

    Try that and see what happens.

  11. #11
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    with your modification the code now compiles.

    initially i would get an immediate stack trace and runtime error because the "loadstockNames" method had problems (name mistakes) i fixed those, and now the stockNames load into the combobox, but when i click the JButton i get a an error, and nothing happens. here is the latest code, pointers?

    Java Code:
    // Exercise 26.11: StockPortfolio.java
    // Displays a client's stock portfolio.
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.text.*;
    import javax.swing.*;
    
    public class StockPortfolio extends JFrame
    {
       // JLabels for prompt
       private JLabel prompt1JLabel;
       private JLabel prompt2JLabel; 
    
       // JComboBox for stock names
       private JComboBox stockNamesJComboBox;
    
       // JButton for stock information
       private JButton stockInfoJButton;
    
       // JPanel for displaying stock information
       private JPanel stockInfoJPanel;
    
       // JLabel and JTextField for stock name
       private JLabel stockNameJLabel; 
       private JTextField stockNameJTextField;
    
       // JLabel and JTextField for stock symbol
       private JLabel stockSymbolJLabel;
       private JTextField stockSymbolJTextField;
    
       // JLabel and JTextField for number of shares
       private JLabel sharesJLabel; 
       private JTextField sharesJTextField;
    
       // JLabel and JTextField for price of shares
       private JLabel priceJLabel;
       private JTextField priceJTextField;
    
       // JLabel and JTextField for total value
       private JLabel totalJLabel;
       private JTextField totalJTextField;
    
       // instance variables for database processing
       private Connection myConnection;
       private Statement myStatement;
       private ResultSet myResultSet;
    
       // constructor
       public StockPortfolio( String databaseDriver, String databaseURL )
       {
    	   // establish a connection to db
    	   try
    	   {
    		   Class.forName ( databaseDriver );
    		   
    		   // connect to a database
    		   myConnection =
    		   	DriverManager.getConnection (databaseURL );
    		   	
    		   	// create Statement for executing SQL
    		   	myStatement = myConnection.createStatement();
    	   }
    	   catch ( SQLException exception )
    	   {
    		   exception.printStackTrace();
    	   }
    	   catch ( ClassNotFoundException exception )
    	   {
    		   exception.printStackTrace();
    	   }
    	   
          createUserInterface(); // set up GUI
    
       } // end constructor
    
       // create and position GUI components; register event handlers
       private void createUserInterface()
       {
          // get content pane for attaching GUI components
          Container contentPane = getContentPane();
          
          // enable explicit positioning of GUI components
          contentPane.setLayout( null );
    
          // set up prompt1JLlabel
          prompt1JLabel = new JLabel();
          prompt1JLabel.setBounds( 8, 16, 350, 16 );
          prompt1JLabel.setText( "Select the name of " +
             "the stock for which you want " );
          contentPane.add( prompt1JLabel );
    
          // set up prompt2JLabel
          prompt2JLabel = new JLabel();
          prompt2JLabel.setBounds( 8, 32, 350, 16 );
          prompt2JLabel.setText( "information, and then " +
             "press the Stock Information button." );
          contentPane.add( prompt2JLabel );
          
          // set up stockNamesJComboBox 
          stockNamesJComboBox = new JComboBox();
          stockNamesJComboBox.setBounds( 76, 65, 200, 26 );
          stockNamesJComboBox.addItem( "" );
          contentPane.add( stockNamesJComboBox );
          
          // load stock names into stockNamesJComboBox
          loadStockNames();
    
          // set up stockInfoJButton
          stockInfoJButton = new JButton();
          stockInfoJButton.setBounds( 100, 100, 150, 23 );
          stockInfoJButton.setText( "Stock Information" );
          contentPane.add( stockInfoJButton );
          stockInfoJButton.addActionListener(
    
             new ActionListener()  // anonymous inner class
             {
                // event handler called when stockInfoJButton is clicked
                public void actionPerformed( ActionEvent event )
                {
                   stockInfoJButtonActionPerformed( event );
                }
    
             } // end anonymous inner class
    
          ); // end addActionLstener
    
          // set up stockInfoJPanel
          stockInfoJPanel = new JPanel();
          stockInfoJPanel.setBounds( 18, 145, 300, 192 );
          stockInfoJPanel.setLayout( null );
          stockInfoJPanel.setBorder( BorderFactory.createTitledBorder( 
             BorderFactory.createEtchedBorder(), "Stock Info" ) );
          contentPane.add( stockInfoJPanel );
    
          // set up stockNameJLabel
          stockNameJLabel = new JLabel();
          stockNameJLabel.setBounds( 8, 24, 150, 23 );
          stockNameJLabel.setText( "Stock name:" );
          stockInfoJPanel.add( stockNameJLabel );
    
          // set up stockNameJTextField
          stockNameJTextField = new JTextField();
          stockNameJTextField.setBounds( 158, 24, 125, 24 );
          stockNameJTextField.setEditable( false );
          stockNameJTextField.setBorder( 
             BorderFactory.createLoweredBevelBorder() );
          stockNameJTextField.setHorizontalAlignment( 
             JTextField.CENTER );
          stockInfoJPanel.add( stockNameJTextField );
    
          // set up stockSymbolJLabel
          stockSymbolJLabel = new JLabel();
          stockSymbolJLabel.setBounds( 8, 56, 150, 23 );
          stockSymbolJLabel.setText( "Stock symbol:" );
          stockInfoJPanel.add( stockSymbolJLabel );
    
          // set up stockSymbolJTextField
          stockSymbolJTextField = new JTextField();
          stockSymbolJTextField.setBounds( 158, 56, 125, 24 );
          stockSymbolJTextField.setEditable( false );
          stockSymbolJTextField.setBorder( 
             BorderFactory.createLoweredBevelBorder() );
          stockSymbolJTextField.setHorizontalAlignment( 
             JTextField.CENTER );
          stockInfoJPanel.add( stockSymbolJTextField );
    
          // set up sharesJLabel
          sharesJLabel = new JLabel();
          sharesJLabel.setBounds( 8, 88, 150, 23 );
          sharesJLabel.setText( "Number of shares:" );
          stockInfoJPanel.add( sharesJLabel );
    
          // set up sharesJTextField
          sharesJTextField = new JTextField();
          sharesJTextField.setBounds( 158, 88, 125, 24 );
          sharesJTextField.setEditable( false );
          sharesJTextField.setBorder( 
             BorderFactory.createLoweredBevelBorder() );
          sharesJTextField.setHorizontalAlignment( JTextField.CENTER );
          stockInfoJPanel.add( sharesJTextField );
    
          // set up priceJLabel
          priceJLabel = new JLabel();
          priceJLabel.setBounds( 8, 120, 150, 23 );
          priceJLabel.setText( "Price per share:" );
          stockInfoJPanel.add( priceJLabel );
    
          // set up priceJTextField
          priceJTextField = new JTextField();
          priceJTextField.setBounds( 158, 120, 125, 24 );
          priceJTextField.setEditable( false );
          priceJTextField.setBorder( 
             BorderFactory.createLoweredBevelBorder() );
          priceJTextField.setHorizontalAlignment( JTextField.CENTER );
          stockInfoJPanel.add( priceJTextField );
    
          // set up totalJLabel
          totalJLabel = new JLabel();
          totalJLabel.setBounds( 8, 152, 150, 23 );
          totalJLabel.setText( "Total value:" );
          stockInfoJPanel.add( totalJLabel );
    
          // set up totalJTextField
          totalJTextField = new JTextField();
          totalJTextField.setBounds( 158, 152, 125, 24 );
          totalJTextField.setEditable( false );
          totalJTextField.setBorder( 
             BorderFactory.createLoweredBevelBorder() );
          totalJTextField.setHorizontalAlignment( JTextField.CENTER );
          stockInfoJPanel.add( totalJTextField );
    
          // ensure database connection is closed 
          // when user quits application
          addWindowListener(
    
             new WindowAdapter()  // anonymous inner class
             {
                public void windowClosing( WindowEvent event )
                {
                   frameWindowClosing( event );
                }
    
             } // end anonymous inner class
    
          ); // end addWindowListener
    
          // set properties of application's window
          setTitle( "Stock Portfolio" ); // set title bar string
          setSize( 350, 380 );           // set window size
          setVisible( true );            // display window
    
       } // end method createUserInterface
    
       // load stock names into stockNamesJComboBox
       private void loadStockNames()
       {
          // add stock names in database to stockNamesJComboBox
          try
          {
    	      myResultSet = myStatement.executeQuery(
    	      	"SELECT stockName FROM stockInformation" );
    	      
    	      // add stockNames to stockNamesJComboBox
    	      while ( myResultSet.next() )
    	      {
    		      stockNamesJComboBox.addItem(
    		      	myResultSet.getString ( "stockName" ) );
    		  }
    		  
    		  myResultSet.close(); // close myResultSet
    		  
    	  }// end try
    	  
    	  catch ( SQLException exception)
    	  {
    		  exception.printStackTrace();
    	  }
          
       } // end method loadStockNames
    
       // user clicked stockInfoJButton
       private void stockInfoJButtonActionPerformed( ActionEvent event )
       {
    	   // get selected stock
    	  String stockName = 
    	  	( String ) stockNamesJComboBox.getSelectedItem(); 
    	  	
    	  	//display stock data
    	  	displayStockData ( stockName );
    	  	
    	} // end method stockInfoJButtonActionPerformed
    	
    	//display stock information
    	private void displayStockData ( String stockName )
    	{
    		//display stock name, stock symbol, shares and price
    		try
    		{
    			//get stock name, stock symbol and shares
    			myResultSet = myStatement.executeQuery( "SELECT stockSymbol,"
    				+ " shares, price FROM stockInformation WHERE " +
    				"stockName = " + ( stockName ) );
    			
    			// non empty result
    			if (myResultSet.next () )
    			{
    				stockNameJTextField.setText(
    					myResultSet.getString( "stockName" ) );
    				stockSymbolJTextField.setText(
    					myResultSet.getString( "stockSymbol" ) );
    				sharesJTextField.setText(
    					myResultSet.getString( "shares" ) );
    					
    				DecimalFormat price = new DecimalFormat( "$0.00" );
    				
    				priceJTextField.setText(	
    					myResultSet.getString( "price" ) );
    			}
    			
    			myResultSet.close(); // close myResultSet
    			
    			
    			
    		}
    		catch ( SQLException exception )
          	{
             	exception.printStackTrace();
          	}
    	}// end method display stock data
    	
    	// calculate total value
    	private String computeTotalValue( int shares, double price )throws SQLException
    	{
    		
    		//get shares and price
    		shares = myResultSet.getInt( "shares" );
    		price = myResultSet.getDouble( "price" );
    
    		
    		// define display format
    		DecimalFormat dollars = new DecimalFormat( "$0.00" );
    
    		return dollars.format( shares * price );
    
    	} // end method computeTotalValue
    
       // user close window
       private void frameWindowClosing( WindowEvent event )
       {
          // close myStatement and database connection
          try
          {
             myStatement.close();
             myConnection.close();
          }
          catch ( SQLException sqlException )
          {
             sqlException.printStackTrace();
          }
          finally
          {
             System.exit( 0 );
          }
          
       }  // end method frameWindowClosing
    	
       // method main
       public static void main( String[] args )
       {
          // check command-line arguments
          if ( args.length == 2 )
          {
             // get command-line arguments
             String databaseDriver = args[ 0 ];
             String databaseURL = args[ 1 ];
    
             // create new StockPortfolio
             StockPortfolio application = 
                new StockPortfolio( databaseDriver, databaseURL );
          }
          else
          {
             System.out.println( "Usage: java StockPortfolio " + 
                "databaseDriver databaseURL" );
          }
    
       } // end method main
    
    } // end class StockPortfolio

  12. #12
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    my mistake, here is the error:

    java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error (m
    issing operator) in query expression 'stockName = CVS Corp'.

  13. #13
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    when i click the JButton i get a an error
    Is this error coming from within displayStockData()? (It's a good idea to post the entire printStackTrace() output)

    Java Code:
    myResultSet = myStatement.executeQuery( "SELECT stockSymbol,"
            + " shares, price FROM stockInformation WHERE " +
            "stockName = " + ( stockName ) );

    I'm wondering about this and the fact that if stockName has the value "CVS Corp" then the space may be causing problems. The database may be saying: he wants data where stockName is CSV but wtf is Corp all about - it's missing an operator.

    If other selections (without spaces in the name) are OK this would confirm that the space is the problem.

    In this case you could try putting some quotes in as part of the sql string. But a much better way is to use a PreparedStatement:

    Java Code:
    // instance variables for database processing
    private Connection myConnection;
    private Statement myStatement;
    private PreparedStatement stockDataPS;  // <---
    private ResultSet myResultSet;
    
    public StockPortfolio( String databaseDriver, String databaseURL )
    {
        // ...
        // create Statement for executing SQL
        myStatement = myConnection.createStatement();
        stockDataPS = myConnection.prepareStatement(
                "SELECT stockSymbol, shares, price FROM stockInformation WHERE stockName = ?");
        // ...
    }
    
    // user clicked stockInfoJButton
    private void stockInfoJButtonActionPerformed( ActionEvent event )
    {
        //...
        private void displayStockData ( String stockName )
        {
            //display stock name, stock symbol, shares and price
            try
            {
                //get stock name, stock symbol and shares
                stockDataPS.setString(1, stockName); // <-- sets the ?
                myResultSet = stockDataPS.executeQuery();
                //...

    Prepared statements are designed for reuse, dealing with quoting and other formatting problems in a database independent way, and dealing with "malicious" values being inserted into the sql string. (It is possible to give stockName a value so that the resulting sql query did nasty things to your database.)

    ---------------------------

    I don't know an awful lot about databases - but I'm sure if I'm putting you wrong here someone will jump in and say so!

    [Edit] Again forgot a critical bit of code... ;(

  14. #14
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    all of the "stockNames" have spaces in them, not that im looking at them, so obviously an error occurs with all of them. here is the entire stack trace error.


    Java Code:
    c:\SimplyJava\StockPortfolio>java StockPortfolio sun.jdbc.odbc.JdbcOdbcDriver jd
    bc:odbc:stocks
    java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error (m
    issing operator) in query expression 'stockName = Yahoo INC'.
            at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6957)
            at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)
            at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(JdbcOdbc.java:3110)
            at sun.jdbc.odbc.JdbcOdbcStatement.execute(JdbcOdbcStatement.java:338)
            at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(JdbcOdbcStatement.java:2
    53)
            at StockPortfolio.displayStockData(StockPortfolio.java:281)
            at StockPortfolio.stockInfoJButtonActionPerformed(StockPortfolio.java:27
    0)
            at StockPortfolio.access$000(StockPortfolio.java:9)
            at StockPortfolio$1.actionPerformed(StockPortfolio.java:121)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:19
    95)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.jav
    a:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242
    )
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:236)
            at java.awt.Component.processMouseEvent(Component.java:6267)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
            at java.awt.Component.processEvent(Component.java:6032)
            at java.awt.Container.processEvent(Container.java:2041)
            at java.awt.Component.dispatchEventImpl(Component.java:4630)
            at java.awt.Container.dispatchEventImpl(Container.java:2099)
            at java.awt.Component.dispatchEvent(Component.java:4460)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577
    )
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
    
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
            at java.awt.Container.dispatchEventImpl(Container.java:2085)
            at java.awt.Window.dispatchEventImpl(Window.java:2478)
            at java.awt.Component.dispatchEvent(Component.java:4460)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre
    ad.java:269)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.
    java:184)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:174)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

  15. #15
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    at StockPortfolio.displayStockData(StockPortfolio.jav a:281)

    Thanks. That confirms where the exception is happening.

    Did you try using a prepared statement?

  16. #16
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    I have not tried using a prepared statement yet. I have never used one before, so im trying to understand exactly how it works.

    you mentioned trying a simply way with quotes, what would i need to do with that first, to try that out, so im sure that in the final issue?

  17. #17
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    Java Code:
    myResultSet = myStatement.executeQuery( "SELECT stockSymbol,"
            + " shares, price FROM stockInformation WHERE " +  
            "stockName = \'" + ( stockName )  + "\'");

    I'm not sure whether single or double quotes are needed. But I am quite sure that prepared statements are better.

  18. #18
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    i used your code adjustment, and got this:
    Java Code:
    c:\SimplyJava\StockPortfolio>javac StockPortfolio.java
    StockPortfolio.java:283: cannot find symbol
    symbol  : class stockName
    location: class StockPortfolio
                                    "stockName = '" + ( stockName )"'" );
                                                        ^
    1 error
    i also found a similar example in this chapters book, identical to yours, but without the backslashes.

    i tried both ways, with and without the backslash and got the same compile error.

  19. #19
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    You've left a + sign out. (Another cost of rolling your own sql expression ;)

    Java Code:
    "stockName = '" + ( stockName ) [b]+[/b] "'" );

  20. #20
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    ahhhhh......man im a rookie!

    ok, so it compiles, not at runtime, another error, this time "Column not Found"

    wow, im terrible at this!

    entire stacktrace:

    Java Code:
    c:\SimplyJava\StockPortfolio>java StockPortfolio sun.jdbc.odbc.JdbcOdbcDriver jd
    bc:odbc:stocks
    java.sql.SQLException: Column not found
            at sun.jdbc.odbc.JdbcOdbcResultSet.findColumn(JdbcOdbcResultSet.java:185
    0)
            at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.java:411)
    
            at StockPortfolio.displayStockData(StockPortfolio.java:288)
            at StockPortfolio.stockInfoJButtonActionPerformed(StockPortfolio.java:27
    0)
            at StockPortfolio.access$000(StockPortfolio.java:9)
            at StockPortfolio$1.actionPerformed(StockPortfolio.java:121)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:19
    95)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.jav
    a:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242
    )
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:236)
            at java.awt.Component.processMouseEvent(Component.java:6267)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
            at java.awt.Component.processEvent(Component.java:6032)
            at java.awt.Container.processEvent(Container.java:2041)
            at java.awt.Component.dispatchEventImpl(Component.java:4630)
            at java.awt.Container.dispatchEventImpl(Container.java:2099)
            at java.awt.Component.dispatchEvent(Component.java:4460)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577
    )
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
    
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
            at java.awt.Container.dispatchEventImpl(Container.java:2085)
            at java.awt.Window.dispatchEventImpl(Window.java:2478)
            at java.awt.Component.dispatchEvent(Component.java:4460)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre
    ad.java:269)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.
    java:184)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:174)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    if i better understood reading the stack trace i could try some things, but im not really sure what im reading....

Page 1 of 3 123 LastLast

Similar Threads

  1. Have I done this exercise right?
    By ccie007 in forum New To Java
    Replies: 7
    Last Post: 09-28-2010, 06:54 PM
  2. Exercise for java 3d
    By armiri in forum Java 2D
    Replies: 2
    Last Post: 05-14-2010, 12:14 AM
  3. Exercise for java 3d
    By armiri in forum Java Software
    Replies: 3
    Last Post: 05-14-2010, 12:13 AM
  4. Help needed with Java exercise - Including arrays - Reward
    By TheDarkReverend in forum New To Java
    Replies: 7
    Last Post: 10-23-2008, 03:52 AM
  5. I/O exercise
    By Feldom in forum New To Java
    Replies: 1
    Last Post: 10-28-2007, 05:48 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •