Extra exercises for Murach¡¯s Beginning Java with Eclipse Chapter 21 Extra Exercise:
Save rectangle data in a database
In this exercise, you¡¯ll modify the Area and Perimeter application so it stores the results of its calculations in a database.
Review the application
1. Download and extract ch21_ex3_AreaAndPerimeter into your Eclipse Workspace.
2. Import the ch21_ex3AreaAndPerimeter project into the Eclipse IDE.
3. Open the classes and review the code. Note that the Rectangle class provides a constructor that can create a Rectangle object from its length and width.
4. Run the application to make sure it works correctly.
Review the contents of the Shapes.sqlite database
5. Start DB Browser for SQLite.
6. Open the Shapes.sqlite database located in the Ch21_ex3_AreaAndPerimeter folder.
7. Click the Browse Data tab and review the contents of the Rectangle table. The ID column contains the automatically incremented primary key.
Add the SQLite database driver to the project
8. In Eclipse, right-click on the project name, select Build Path¡úAdd External Archives, and use the resulting dialog box to select the JAR file that contains the driver. The JAR file is in the murach\java\db folder.
Create a file DB class
9. Create a class named RectangleDB. Then, add the following methods to the RectangleDB class:
private static Connection getConnection()
public static void add(Rectangle r)
public static List
10. Add code to the getConnection method so that it makes a connection to the Shapes.sqlite database. Use the example on page 687 as a guide.
11. Add code to the add method so that it inserts a row for the specified Rectangle object into the Rectangle table. Only the length and width columns should be populated. Use the example on page 691 as a guide.
12. Add code to the getAll method so that it returns an ArrayList object that contains one Rectangle object for each row in the Rectangle table. Use the example on page 689 as a guide.
Use the file DB class
13. In the Main class, add code to the while loop that uses the add method of the RectangleDB class to insert a Rectangle object. Use the example on page 693 as a guide.
Extra exercises for Murach¡¯s Beginning Java with Eclipse
14. After the code that prints the ¡°Bye!¡± message, add code that uses the getAll method of the RectangleDB class to get an ArrayList of Rectangle objects. Use the example on page 693 as a guide.
15. Add a for each loop that prints each Rectangle object to the console.
16. Run the application to make sure it works correctly. The output should appear as follows, depending on the contents of the table:
Welcome to the Area and Perimeter Calculator
Enter length: 500
Enter width: 400
Area: 200,000.000
Perimeter: 1,800.000
Continue? (y/n): n
Bye!
RECTANGLES (length|width|area|perimeter):
100.0|200.0|20000.0|600.0
300.0|400.0|120000.0|1400.0
100.0|50.0|5000.0|300.0
100.0|75.0|7500.0|350.0
500.0|400.0|200000.0|1800.0