SlideShare a Scribd company logo
1 of 19
Download to read offline
database properties:
jdbc.url=jdbc:derby:BigJavaDB;create=true
# With other databases, you may need to add entries such as these
# jdbc.username=admin
# jdbc.password=secret
# jdbc.driver=org.apache.derby.jdbc.EmbeddedDriver
InventoryDB:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
/**
* An inventory consisting of multiple products.
* Uses a JDBC database interface to manage the data.
*/
public class InventoryDB
{
/**
* Create or re-create the ProductsDB table in the database with
* some default data.
* @param conn - Database connection
* @throws SQLException - on any database error
*/
public void initialize() throws SQLException
{
try (Connection conn = SimpleDataSource.getConnection())
{
try (Statement stat = conn.createStatement())
{
try
{
// This will fail if the table doesn't exist. That is OK.
stat.execute("DROP TABLE ProductsDB");
}
catch (SQLException e)
{
System.out.println("Notice: Exception during DROP TABLE Products: " +
e.getMessage() + " (This is expected when the database is empty)");
}
// If an execption occurs after this point, allow it to be thrown.
// ProductsDB table: Product_Code, Description, Quantity, Price
stat.execute("CREATE TABLE ProductsDB (Product_Code VARCHAR(7),
Description VARCHAR(40), Quantity INT, Price DECIMAL(10,2))");
// Add default list of products using parallel arrays.
String productCodes[] = {"116-064", "257-535", "643-119", "011-025"};
String descriptions[] = {"Toaster", "Hair dryer", "Car vacuum", "Gallon 2%
Milk"};
int quantities[] = {50, 75, 43, 111};
double prices[] = {24.95, 29.95, 19.99, 2.95};
for (int i = 0; i < productCodes.length; i++)
{
ProductDB a = new ProductDB(productCodes[i]);
a.addProduct(descriptions[i], quantities[i], prices[i]);
System.out.printf("Notice: inserted product %s %s %d %.2f ",
productCodes[i], descriptions[i], quantities[i], prices[i]);
}
}
}
}
/**
* Obtain an array list of all the Products in the Inventory.
* @return arraylist of ProductDB
* @throws SQLException - on any database error
*/
public ArrayList getAllProducts() throws SQLException
{
ArrayList products = new ArrayList();
try (Connection conn = SimpleDataSource.getConnection())
{
try (Statement stat = conn.createStatement())
{
// ProductsDB table: AccountNumber, Balance
ResultSet result = stat.executeQuery("SELECT Product_Code FROM Products");
while (result.next())
{
ProductDB a = new ProductDB(result.getString(1));
products.add(a);
}
}
}
return products;
}
/**
* Finds a product with a given code or null if not found.
* @param productCode the number to find
* @return the product with the given code
* @throws SQLException - on any database error
*/
public ProductDB find(String productCode) throws SQLException
{
try (Connection conn = SimpleDataSource.getConnection())
{
// Does the product exist?
try (PreparedStatement stat = conn.prepareStatement("SELECT COUNT(*) FROM
ProductsDB WHERE Product_Code = ?"))
{
stat.setString(1, productCode);
ResultSet result = stat.executeQuery();
// There must be one row returned.
result.next();
if (result.getInt(1) == 0)
{
return null;
}
// Product exists: return it.
ProductDB a = new ProductDB(productCode);
return a;
}
}
}
/**
* Gets the sum of the products in this inventory.
* @return the sum of the balances
* @throws SQLException - on any database error
*/
public double getTotalValue() throws SQLException
{
double total = 0;
ArrayList products = getAllProducts();
for (ProductDB a : products)
{
total = total + a.getTotalValue();
}
return total;
}
/**
* Return a string that describes all the products in the inventory.
*/
public String toString()
{
StringBuffer sb = new StringBuffer();
ArrayList products;
try
{
products = getAllProducts();
for (ProductDB a : products)
{
sb.append(a.toString());
}
}
catch (SQLException e)
{
sb.append("SQLException occurred: " + e.getMessage());
}
return sb.toString();
}
}
InventoryMgr:
import java.io.IOException;
import java.sql.SQLException;
import java.util.Scanner;
public class InventoryMgr
{
public static void main(String[] args) throws ClassNotFoundException, IOException {
SimpleDataSource.init("database.properties");
Scanner in = new Scanner(System.in);
InventoryDB myInventory = new InventoryDB();
boolean done = false;
while (!done)
{
try
{
System.out.println("I) Initialize database A)dd Product P)urchase Products S)ell
Products C)heck Product Q)uit");
String input = in.nextLine().toUpperCase();
if (input.equals("I"))
{
System.out.println("Enter 'YES' if you wish to reinitialize the inventory: ");
String answer = in.nextLine();
if (answer.equalsIgnoreCase("YES"))
myInventory.initialize();
else
System.out.println("OK, existing data preserved");
}
else if (input.equals("A"))
{
String productCode = promptForWord(in, "Enter new product code: ");
if (myInventory.find(productCode) != null)
{
System.out.printf("Error: product code %d already exists. ", productCode);
}
else
{
String desc = promptForWord(in, "Enter new product description: ");
int qty = promptForInt(in, "Enter new product quantity: ");
double price = promptForDouble(in, "Enter new product price: ");
ProductDB a = new ProductDB(productCode);
a.addProduct(desc, qty, price);
}
}
else if (input.equals("P"))
{
String productCode = promptForWord(in, "Enter product code for purchase: ");
ProductDB a = myInventory.find(productCode);
if (a == null)
{
System.out.printf("Error: product code %s does not exist. ", productCode);
}
else
{
System.out.printf("Product %s: %s ", productCode, a.toString());
int qty = promptForInt(in, "Enter number of products purchased: ");
a.purchased(qty);
System.out.printf("Product %s now has quantity %d. ", productCode,
a.getQuantity());
}
}
else if (input.equals("S"))
{
String productCode = promptForWord(in, "Enter product code for sale: ");
ProductDB a = myInventory.find(productCode);
if (a == null)
{
System.out.printf("Error: product %s does not exist. ", productCode);
}
else
{
System.out.printf("Product %s: %s ", productCode, a.toString());
int quantitySold = promptForInt(in, "Enter number of products sold: ");
if (a.getQuantity() < quantitySold)
{
System.out.printf("Error: Product %s quantity %d is less than requested
quantity %d ",
productCode, a.getQuantity(), quantitySold);
}
else
{
a.sold(quantitySold);
System.out.printf("Product %s now has quantity %d. ", productCode,
a.getQuantity());
}
}
}
else if (input.equals("C"))
{
String productCode = promptForWord(in, "Enter product code to check: ");
ProductDB a = myInventory.find(productCode);
if (a == null)
{
System.out.printf("Error: product %s does not exist. ", productCode);
}
else
{
System.out.printf("Product: %s %s ", productCode, a.toString());
}
}
else if (input.equals("Q"))
{
done = true;
}
}
catch (SQLException e)
{
System.out.printf("Database exception: %s ", e.getMessage());
e.printStackTrace();
}
}
}
/**
* Ask the user for an integer input. Repeat until successful.
* @param in Scanner for reading input
* @param prompt String to show to user
* @return value entered by user
*/
public static int promptForInt(Scanner in, String prompt)
{
int result = 0;
boolean done = false;
while (!done)
{
System.out.print(prompt);
String inputStr = in.nextLine().trim();
try
{
result = Integer.parseInt(inputStr);
done = true;
}
catch (NumberFormatException e)
{
System.out.printf("Error: '%s' was not recognized as an integer. Please try again. ",
inputStr);
}
}
return result;
}
/**
* Ask the user for a double precision number. Repeat until successful.
* @param in Scanner for reading input
* @param prompt String to show to user
* @return value entered by user
*/
public static double promptForDouble(Scanner in, String prompt)
{
double result = 0;
boolean done = false;
while (!done)
{
System.out.print(prompt);
String inputStr = in.nextLine().trim();
try
{
result = Double.parseDouble(inputStr);
done = true;
}
catch (NumberFormatException e)
{
System.out.printf("Error: '%s' was not recognized as a double. Please try again. ",
inputStr);
}
}
return result;
}
/**
* Ask the user for a single word as a string. Repeat until successful.
* @param in Scanner for reading input
* @param prompt String to show to user
* @return value entered by user
*/
public static String promptForWord(Scanner in, String prompt)
{
System.out.print(prompt);
return in.nextLine().trim();
}
}
ProductDB:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
A product has a code, description, price, and quantity in stock.
This implementation uses a database table to contain its data.
*/
public class ProductDB
{
private String productCode;
/**
* Constructs a product object for operations on the ProductsDB table.
* @param aProductCode the product code
*/
public ProductDB(String aProductCode)
{
productCode = aProductCode;
}
/**
* Add the data for a product to the database.
* @param description - describes product
* @param quantity - count in inventory
* @throws SQLException - on any database error
*/
public void addProduct(String desc, int qty, double price) throws SQLException
{
try (Connection conn = SimpleDataSource.getConnection())
{
try (PreparedStatement stat = conn.prepareStatement("INSERT INTO ProductsDB
(Product_Code, Description, Quantity, Price) VALUES (?, ?, ?, ?)"))
{
stat.setString(1, productCode);
stat.setString(2, desc);
stat.setInt(3, qty);
stat.setDouble(4, price);
stat.execute();
}
}
}
/**
* Increases the quantity of product when we've
* purchased products to replenish our supply.
* @param number the count of products purchased.
* @throws SQLException - on any database error
*/
public void purchased(int qtyPurchased)
throws SQLException
{
// TODO: Update the ProductsDB table's quantity for this
// object's product code.
}
/**
* Decrease the quantity of product when we've
* sold product to a customer.
* @param qtySold - Number of product sold
* @throws SQLException - on any database error
*/
public void sold(int qtySold)
throws SQLException
{
// TODO: Update the ProductsDB table's quantity for this
// object's product code.
}
/**
* Gets the description for this product.
* @return the product description
*/
public String getDescription()
throws SQLException
{
// TODO: Query the ProductsDB table for the description
// for this object's product code.
return ""; // Replace this with the actual description from the ProductsDB table
}
/**
* Gets the quantity of this product.
* @return the current quantity
* @throws SQLException - on any database error
*/
public int getQuantity()
throws SQLException
{
// Query the ProductsDB table for the quantity
// of this object's product code.
try (Connection conn = SimpleDataSource.getConnection())
{
try (PreparedStatement stat =
conn.prepareStatement("SELECT Quantity FROM ProductsDB WHERE Product_Code
= ?"))
{
// Set the value for the first '?' in the prepared statement.
stat.setString(1, productCode);
// Run the query.
ResultSet result = stat.executeQuery();
// There should be only one row in the result set. Advance to
// the first row and get the computed total value of this product.
result.next();
// The computed value is in the first column of this first row.
return result.getInt(1);
}
}
}
/**
* Gets the price of this product.
* @return the current price
* @throws SQLException - on any database error
*/
public double getPrice()
throws SQLException
{
// Query the ProductsDB table for the price
// of this object's product code.
try (Connection conn = SimpleDataSource.getConnection())
{
try (PreparedStatement stat = conn.prepareStatement("SELECT Price FROM
ProductsDB WHERE Product_Code = ?"))
{
// Set the value for the first '?' in the prepared statement.
stat.setString(1, productCode);
ResultSet result = stat.executeQuery();
// There should be only one row in the result set. Advance to
// the first row and get the computed total value of this product.
result.next();
// The computed value is in the first column of this first row.
return result.getDouble(1);
}
}
}
/**
* Gets the code for this product.
* @return the product code
*/
public String getCode()
{
// We keep the product code as the key in the object.
return productCode;
}
/**
* Get the total value in inventory of this product
* (quantity times price).
* return value
* @throws SQLException - on any database error
*/
public double getTotalValue()
throws SQLException
{
// Query the ProductsDB table for the quantity and price
// of this object's product code.
try (Connection conn = SimpleDataSource.getConnection())
{
try (PreparedStatement stat = conn.prepareStatement("SELECT Quantity * Price FROM
ProductsDB WHERE Product_Code = ?"))
{
stat.setString(1, productCode);
ResultSet result = stat.executeQuery();
// There should be only one row in the result set. Advance to
// the first row and get the computed total value of this product.
result.next();
// The computed value is in the first column of this first row.
return result.getDouble(1);
}
}
}
/**
* Return a string describing this product.
*/
public String toString()
{
String result;
try
{
// Query the ProductsDB table for the description, quantity, and price
// of this object's product code.
try (Connection conn = SimpleDataSource.getConnection())
{
try (PreparedStatement stat = conn.prepareStatement("SELECT Description, Quantity,
Price FROM ProductsDB WHERE Product_Code = ?"))
{
stat.setString(1, productCode);
ResultSet rs = stat.executeQuery();
// There should be only one row in the result set. Advance to
// the first row and get the computed total value of this product.
rs.next();
result = String.format("Product: %s %s %d %.2f",
productCode, rs.getString(1), rs.getInt(2), rs.getDouble(3));
}
}
}
catch (SQLException e)
{
result = "SQLException while getting product info: " + e.getMessage();
}
return result;
}
}
SimpleDataSource:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
A simple data source for getting database connections.
*/
public class SimpleDataSource
{
private static String url;
private static String username;
private static String password;
/**
Initializes the data source.
@param fileName the name of the property file that
contains the database driver, URL, username, and password
*/
public static void init(String fileName)
throws IOException, ClassNotFoundException
{
Properties props = new Properties();
FileInputStream in = new FileInputStream(fileName);
props.load(in);
String driver = props.getProperty("jdbc.driver");
url = props.getProperty("jdbc.url");
username = props.getProperty("jdbc.username");
if (username == null) username = "";
password = props.getProperty("jdbc.password");
if (password == null) password = "";
if (driver != null)
Class.forName(driver);
}
/**
Gets a connection to the database.
@return the database connection
*/
public static Connection getConnection() throws SQLException
{
return DriverManager.getConnection(url, username, password);
}
} 2. (20 points) Complete a Java program named InventoryMgr that maintains products in a
database The code to initialize the ProductDB database table and add a set of products is
provided. Finish the code needed in these methods in ProductDB.java to update or query the
database purchased (int quantityPurchased) sold (int quantitytsold) getDescription() Hint: Look
at the getPrice) and getQuantity0 methods to see how you might write the getDescription)
method's code, and the addProduct) method to see an example of how you might write the code
for the purchased) and sold) methods Download the derby.jar file and save it where Eclipse can
use it, such as on your Desktop Download the Homework4Files.zip file containing these files
database.properties ProductDB.java InventoryDB.java Invento SimpleDataSource.java
Properties file for the database connection Class to update and Class to initialize the ProductsDB
table and operate on all Main method with user interface SimpleDataSource class to simplity
database connections roductdb rows cts ava To run the Inventory Mgr Java program in Eclipse,
create a new project, copy all of the Java files into the src folder of your project, and copy the
database.properties file into the project's folder. Open the Project's Properties dialog and select
Java Build Paths, then click the Libraries tab. Click the Add JARs button, use the Open dialog to
find the file derby.jar, and click the Open button. Click OK to save these changes to the Project's
properties Here is a sample run of the program the user's input is in green
Solution
Please find the three functions with explanation below
/**
* Increases the quantity of product when we've
* purchased products to replenish our supply.
* @param number the count of products purchased.
* @throws SQLException - on any database error
*/
public void purchased(int qtyPurchased)
throws SQLException
{
// TODO: Update the ProductsDB table's quantity for this
// object's product code.
//Getting the current quantity count from Db and then incrementing it with the purchased value
int Quantity= getQuantity()+qtyPurchased;
try (Connection conn = SimpleDataSource.getConnection())
{
try (PreparedStatement stat =
conn.prepareStatement("UPDATE ProductsDB SET Quantity="+Quantity +" WHERE
Product_Code = ?"))
{
// Set the value for the first '?' in the prepared statement.
stat.setString(1, productCode);
// Run the query.
stat.executeUpdate();
}
}
}
/**
* Decrease the quantity of product when we've
* sold product to a customer.
* @param qtySold - Number of product sold
* @throws SQLException - on any database error
*/
public void sold(int qtySold)
throws SQLException
{
// TODO: Update the ProductsDB table's quantity for this
// object's product code.
//Getting the current quantity count from Db and then subtracting the sold value from it
int Quantity= getQuantity()-qtySold;
try (Connection conn = SimpleDataSource.getConnection())
{
try (PreparedStatement stat =
conn.prepareStatement("UPDATE ProductsDB SET Quantity="+Quantity +" WHERE
Product_Code = ?"))
{
// Set the value for the first '?' in the prepared statement.
stat.setString(1, productCode);
// Run the query.
stat.executeUpdate();
}
}
}
/**
* Gets the description for this product.
* @return the product description
*/
public String getDescription()
throws SQLException
{
// TODO: Query the ProductsDB table for the description
// for this object's product code.
try (Connection conn = SimpleDataSource.getConnection())
{
try (PreparedStatement stat =
conn.prepareStatement("SELECT Description FROM ProductsDB WHERE Product_Code =
?"))
{
// Set the value for the first '?' in the prepared statement.
stat.setString(1, productCode);
// Run the query.
ResultSet result = stat.executeQuery();
// There should be only one row in the result set. Advance to
// the first row and get the description of this product.
result.next();
// The description is in the first column of this first row.
return result.getString(1);
}
}
}

More Related Content

Similar to database propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdf

VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access RunbookTaha Shakeel
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
Selenium my sql and junit user guide
Selenium my sql and junit user guideSelenium my sql and junit user guide
Selenium my sql and junit user guideFahad Shiekh
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVCRichard Paul
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
Should be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdfShould be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdffashionscollect
 
Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0Frost
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsphanleson
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docxhoney725342
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitPeter Wilcsinszky
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptRyan Anklam
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql JOYITAKUNDU1
 
the code below is a recommendation system application to suggest a s.pdf
the code below is a recommendation system application to suggest a s.pdfthe code below is a recommendation system application to suggest a s.pdf
the code below is a recommendation system application to suggest a s.pdfrajatchugh13
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 

Similar to database propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdf (20)

VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access Runbook
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
C# labprograms
C# labprogramsC# labprograms
C# labprograms
 
Selenium my sql and junit user guide
Selenium my sql and junit user guideSelenium my sql and junit user guide
Selenium my sql and junit user guide
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Should be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdfShould be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdf
 
Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnit
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
 
Google guava
Google guavaGoogle guava
Google guava
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
the code below is a recommendation system application to suggest a s.pdf
the code below is a recommendation system application to suggest a s.pdfthe code below is a recommendation system application to suggest a s.pdf
the code below is a recommendation system application to suggest a s.pdf
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 

More from fashiionbeutycare

________ are characterized by small incisors and large premolars wit.pdf
________ are characterized by small incisors and large premolars wit.pdf________ are characterized by small incisors and large premolars wit.pdf
________ are characterized by small incisors and large premolars wit.pdffashiionbeutycare
 
Write a Java program that opens the file, reads all the Grade from t.pdf
Write a Java program that opens the file, reads all the Grade from t.pdfWrite a Java program that opens the file, reads all the Grade from t.pdf
Write a Java program that opens the file, reads all the Grade from t.pdffashiionbeutycare
 
why do Private offices have a high sensible heat ratioSolution.pdf
why do Private offices have a high sensible heat ratioSolution.pdfwhy do Private offices have a high sensible heat ratioSolution.pdf
why do Private offices have a high sensible heat ratioSolution.pdffashiionbeutycare
 
Why is payback and IRR more frequently used than NPV when it comes t.pdf
Why is payback and IRR more frequently used than NPV when it comes t.pdfWhy is payback and IRR more frequently used than NPV when it comes t.pdf
Why is payback and IRR more frequently used than NPV when it comes t.pdffashiionbeutycare
 
What general environmental condition is represented by this assemblag.pdf
What general environmental condition is represented by this assemblag.pdfWhat general environmental condition is represented by this assemblag.pdf
What general environmental condition is represented by this assemblag.pdffashiionbeutycare
 
What are some of the basic features of Excavates Discuss the differe.pdf
What are some of the basic features of Excavates Discuss the differe.pdfWhat are some of the basic features of Excavates Discuss the differe.pdf
What are some of the basic features of Excavates Discuss the differe.pdffashiionbeutycare
 
True or False Disulfides are essential for cone-snail venoms acti.pdf
True or False Disulfides are essential for cone-snail venoms acti.pdfTrue or False Disulfides are essential for cone-snail venoms acti.pdf
True or False Disulfides are essential for cone-snail venoms acti.pdffashiionbeutycare
 
To what extent do GUI editors generally allow developers to modify H.pdf
To what extent do GUI editors generally allow developers to modify H.pdfTo what extent do GUI editors generally allow developers to modify H.pdf
To what extent do GUI editors generally allow developers to modify H.pdffashiionbeutycare
 
The diagram shows a cell during the anaphase stage of mitosis. How wo.pdf
The diagram shows a cell during the anaphase stage of mitosis. How wo.pdfThe diagram shows a cell during the anaphase stage of mitosis. How wo.pdf
The diagram shows a cell during the anaphase stage of mitosis. How wo.pdffashiionbeutycare
 
Thank you for your helpful answer! Consider the following meth.pdf
Thank you for your helpful answer! Consider the following meth.pdfThank you for your helpful answer! Consider the following meth.pdf
Thank you for your helpful answer! Consider the following meth.pdffashiionbeutycare
 
State whether the following statement is true or false The graph of t.pdf
State whether the following statement is true or false The graph of t.pdfState whether the following statement is true or false The graph of t.pdf
State whether the following statement is true or false The graph of t.pdffashiionbeutycare
 
Should Maria’s ethical responsibility to Linda lead her to keep thes.pdf
Should Maria’s ethical responsibility to Linda lead her to keep thes.pdfShould Maria’s ethical responsibility to Linda lead her to keep thes.pdf
Should Maria’s ethical responsibility to Linda lead her to keep thes.pdffashiionbeutycare
 
Revolution in Egypt With 83 million people, Egypt is the most populou.pdf
Revolution in Egypt With 83 million people, Egypt is the most populou.pdfRevolution in Egypt With 83 million people, Egypt is the most populou.pdf
Revolution in Egypt With 83 million people, Egypt is the most populou.pdffashiionbeutycare
 
Question No. 1What updates have been brought by snmpv2 to SNMPv1 c.pdf
Question No. 1What updates have been brought by snmpv2 to SNMPv1 c.pdfQuestion No. 1What updates have been brought by snmpv2 to SNMPv1 c.pdf
Question No. 1What updates have been brought by snmpv2 to SNMPv1 c.pdffashiionbeutycare
 
President Truman belleved that an increase in a na development, which.pdf
President Truman belleved that an increase in a na development, which.pdfPresident Truman belleved that an increase in a na development, which.pdf
President Truman belleved that an increase in a na development, which.pdffashiionbeutycare
 
Pretend you have been asked by the president of the united statesto .pdf
Pretend you have been asked by the president of the united statesto .pdfPretend you have been asked by the president of the united statesto .pdf
Pretend you have been asked by the president of the united statesto .pdffashiionbeutycare
 
Please explain in detail. Why cant Salmonella be infected by lambd.pdf
Please explain in detail. Why cant Salmonella be infected by lambd.pdfPlease explain in detail. Why cant Salmonella be infected by lambd.pdf
Please explain in detail. Why cant Salmonella be infected by lambd.pdffashiionbeutycare
 
Part A Tnsomy 21, or Down syndrome, occurs when there is anormal dplo.pdf
Part A Tnsomy 21, or Down syndrome, occurs when there is anormal dplo.pdfPart A Tnsomy 21, or Down syndrome, occurs when there is anormal dplo.pdf
Part A Tnsomy 21, or Down syndrome, occurs when there is anormal dplo.pdffashiionbeutycare
 
Part 1 List the basic steps in securing an operating system. Assume.pdf
Part 1 List the basic steps in securing an operating system. Assume.pdfPart 1 List the basic steps in securing an operating system. Assume.pdf
Part 1 List the basic steps in securing an operating system. Assume.pdffashiionbeutycare
 
John is 35 years old and recently married with Eva. After they got m.pdf
John is 35 years old and recently married with Eva. After they got m.pdfJohn is 35 years old and recently married with Eva. After they got m.pdf
John is 35 years old and recently married with Eva. After they got m.pdffashiionbeutycare
 

More from fashiionbeutycare (20)

________ are characterized by small incisors and large premolars wit.pdf
________ are characterized by small incisors and large premolars wit.pdf________ are characterized by small incisors and large premolars wit.pdf
________ are characterized by small incisors and large premolars wit.pdf
 
Write a Java program that opens the file, reads all the Grade from t.pdf
Write a Java program that opens the file, reads all the Grade from t.pdfWrite a Java program that opens the file, reads all the Grade from t.pdf
Write a Java program that opens the file, reads all the Grade from t.pdf
 
why do Private offices have a high sensible heat ratioSolution.pdf
why do Private offices have a high sensible heat ratioSolution.pdfwhy do Private offices have a high sensible heat ratioSolution.pdf
why do Private offices have a high sensible heat ratioSolution.pdf
 
Why is payback and IRR more frequently used than NPV when it comes t.pdf
Why is payback and IRR more frequently used than NPV when it comes t.pdfWhy is payback and IRR more frequently used than NPV when it comes t.pdf
Why is payback and IRR more frequently used than NPV when it comes t.pdf
 
What general environmental condition is represented by this assemblag.pdf
What general environmental condition is represented by this assemblag.pdfWhat general environmental condition is represented by this assemblag.pdf
What general environmental condition is represented by this assemblag.pdf
 
What are some of the basic features of Excavates Discuss the differe.pdf
What are some of the basic features of Excavates Discuss the differe.pdfWhat are some of the basic features of Excavates Discuss the differe.pdf
What are some of the basic features of Excavates Discuss the differe.pdf
 
True or False Disulfides are essential for cone-snail venoms acti.pdf
True or False Disulfides are essential for cone-snail venoms acti.pdfTrue or False Disulfides are essential for cone-snail venoms acti.pdf
True or False Disulfides are essential for cone-snail venoms acti.pdf
 
To what extent do GUI editors generally allow developers to modify H.pdf
To what extent do GUI editors generally allow developers to modify H.pdfTo what extent do GUI editors generally allow developers to modify H.pdf
To what extent do GUI editors generally allow developers to modify H.pdf
 
The diagram shows a cell during the anaphase stage of mitosis. How wo.pdf
The diagram shows a cell during the anaphase stage of mitosis. How wo.pdfThe diagram shows a cell during the anaphase stage of mitosis. How wo.pdf
The diagram shows a cell during the anaphase stage of mitosis. How wo.pdf
 
Thank you for your helpful answer! Consider the following meth.pdf
Thank you for your helpful answer! Consider the following meth.pdfThank you for your helpful answer! Consider the following meth.pdf
Thank you for your helpful answer! Consider the following meth.pdf
 
State whether the following statement is true or false The graph of t.pdf
State whether the following statement is true or false The graph of t.pdfState whether the following statement is true or false The graph of t.pdf
State whether the following statement is true or false The graph of t.pdf
 
Should Maria’s ethical responsibility to Linda lead her to keep thes.pdf
Should Maria’s ethical responsibility to Linda lead her to keep thes.pdfShould Maria’s ethical responsibility to Linda lead her to keep thes.pdf
Should Maria’s ethical responsibility to Linda lead her to keep thes.pdf
 
Revolution in Egypt With 83 million people, Egypt is the most populou.pdf
Revolution in Egypt With 83 million people, Egypt is the most populou.pdfRevolution in Egypt With 83 million people, Egypt is the most populou.pdf
Revolution in Egypt With 83 million people, Egypt is the most populou.pdf
 
Question No. 1What updates have been brought by snmpv2 to SNMPv1 c.pdf
Question No. 1What updates have been brought by snmpv2 to SNMPv1 c.pdfQuestion No. 1What updates have been brought by snmpv2 to SNMPv1 c.pdf
Question No. 1What updates have been brought by snmpv2 to SNMPv1 c.pdf
 
President Truman belleved that an increase in a na development, which.pdf
President Truman belleved that an increase in a na development, which.pdfPresident Truman belleved that an increase in a na development, which.pdf
President Truman belleved that an increase in a na development, which.pdf
 
Pretend you have been asked by the president of the united statesto .pdf
Pretend you have been asked by the president of the united statesto .pdfPretend you have been asked by the president of the united statesto .pdf
Pretend you have been asked by the president of the united statesto .pdf
 
Please explain in detail. Why cant Salmonella be infected by lambd.pdf
Please explain in detail. Why cant Salmonella be infected by lambd.pdfPlease explain in detail. Why cant Salmonella be infected by lambd.pdf
Please explain in detail. Why cant Salmonella be infected by lambd.pdf
 
Part A Tnsomy 21, or Down syndrome, occurs when there is anormal dplo.pdf
Part A Tnsomy 21, or Down syndrome, occurs when there is anormal dplo.pdfPart A Tnsomy 21, or Down syndrome, occurs when there is anormal dplo.pdf
Part A Tnsomy 21, or Down syndrome, occurs when there is anormal dplo.pdf
 
Part 1 List the basic steps in securing an operating system. Assume.pdf
Part 1 List the basic steps in securing an operating system. Assume.pdfPart 1 List the basic steps in securing an operating system. Assume.pdf
Part 1 List the basic steps in securing an operating system. Assume.pdf
 
John is 35 years old and recently married with Eva. After they got m.pdf
John is 35 years old and recently married with Eva. After they got m.pdfJohn is 35 years old and recently married with Eva. After they got m.pdf
John is 35 years old and recently married with Eva. After they got m.pdf
 

Recently uploaded

SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project researchCaitlinCummins3
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxAdelaideRefugio
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfPondicherry University
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17Celine George
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...Nguyen Thanh Tu Collection
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhleson0603
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesAmanpreetKaur157993
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppCeline George
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...Gary Wood
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................MirzaAbrarBaig5
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptxPoojaSen20
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismDabee Kamal
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code ExamplesPeter Brusilovsky
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽中 央社
 

Recently uploaded (20)

SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 
Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 

database propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdf

  • 1. database properties: jdbc.url=jdbc:derby:BigJavaDB;create=true # With other databases, you may need to add entries such as these # jdbc.username=admin # jdbc.password=secret # jdbc.driver=org.apache.derby.jdbc.EmbeddedDriver InventoryDB: import java.sql.Connection; import java.sql.ResultSet; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; /** * An inventory consisting of multiple products. * Uses a JDBC database interface to manage the data. */ public class InventoryDB { /** * Create or re-create the ProductsDB table in the database with * some default data. * @param conn - Database connection * @throws SQLException - on any database error */ public void initialize() throws SQLException { try (Connection conn = SimpleDataSource.getConnection()) { try (Statement stat = conn.createStatement()) { try { // This will fail if the table doesn't exist. That is OK. stat.execute("DROP TABLE ProductsDB");
  • 2. } catch (SQLException e) { System.out.println("Notice: Exception during DROP TABLE Products: " + e.getMessage() + " (This is expected when the database is empty)"); } // If an execption occurs after this point, allow it to be thrown. // ProductsDB table: Product_Code, Description, Quantity, Price stat.execute("CREATE TABLE ProductsDB (Product_Code VARCHAR(7), Description VARCHAR(40), Quantity INT, Price DECIMAL(10,2))"); // Add default list of products using parallel arrays. String productCodes[] = {"116-064", "257-535", "643-119", "011-025"}; String descriptions[] = {"Toaster", "Hair dryer", "Car vacuum", "Gallon 2% Milk"}; int quantities[] = {50, 75, 43, 111}; double prices[] = {24.95, 29.95, 19.99, 2.95}; for (int i = 0; i < productCodes.length; i++) { ProductDB a = new ProductDB(productCodes[i]); a.addProduct(descriptions[i], quantities[i], prices[i]); System.out.printf("Notice: inserted product %s %s %d %.2f ", productCodes[i], descriptions[i], quantities[i], prices[i]); } } } } /** * Obtain an array list of all the Products in the Inventory. * @return arraylist of ProductDB * @throws SQLException - on any database error */ public ArrayList getAllProducts() throws SQLException { ArrayList products = new ArrayList(); try (Connection conn = SimpleDataSource.getConnection()) {
  • 3. try (Statement stat = conn.createStatement()) { // ProductsDB table: AccountNumber, Balance ResultSet result = stat.executeQuery("SELECT Product_Code FROM Products"); while (result.next()) { ProductDB a = new ProductDB(result.getString(1)); products.add(a); } } } return products; } /** * Finds a product with a given code or null if not found. * @param productCode the number to find * @return the product with the given code * @throws SQLException - on any database error */ public ProductDB find(String productCode) throws SQLException { try (Connection conn = SimpleDataSource.getConnection()) { // Does the product exist? try (PreparedStatement stat = conn.prepareStatement("SELECT COUNT(*) FROM ProductsDB WHERE Product_Code = ?")) { stat.setString(1, productCode); ResultSet result = stat.executeQuery(); // There must be one row returned. result.next(); if (result.getInt(1) == 0) { return null; }
  • 4. // Product exists: return it. ProductDB a = new ProductDB(productCode); return a; } } } /** * Gets the sum of the products in this inventory. * @return the sum of the balances * @throws SQLException - on any database error */ public double getTotalValue() throws SQLException { double total = 0; ArrayList products = getAllProducts(); for (ProductDB a : products) { total = total + a.getTotalValue(); } return total; } /** * Return a string that describes all the products in the inventory. */ public String toString() { StringBuffer sb = new StringBuffer(); ArrayList products; try { products = getAllProducts(); for (ProductDB a : products) { sb.append(a.toString()); }
  • 5. } catch (SQLException e) { sb.append("SQLException occurred: " + e.getMessage()); } return sb.toString(); } } InventoryMgr: import java.io.IOException; import java.sql.SQLException; import java.util.Scanner; public class InventoryMgr { public static void main(String[] args) throws ClassNotFoundException, IOException { SimpleDataSource.init("database.properties"); Scanner in = new Scanner(System.in); InventoryDB myInventory = new InventoryDB(); boolean done = false; while (!done) { try { System.out.println("I) Initialize database A)dd Product P)urchase Products S)ell Products C)heck Product Q)uit"); String input = in.nextLine().toUpperCase(); if (input.equals("I")) { System.out.println("Enter 'YES' if you wish to reinitialize the inventory: "); String answer = in.nextLine(); if (answer.equalsIgnoreCase("YES")) myInventory.initialize(); else System.out.println("OK, existing data preserved"); } else if (input.equals("A"))
  • 6. { String productCode = promptForWord(in, "Enter new product code: "); if (myInventory.find(productCode) != null) { System.out.printf("Error: product code %d already exists. ", productCode); } else { String desc = promptForWord(in, "Enter new product description: "); int qty = promptForInt(in, "Enter new product quantity: "); double price = promptForDouble(in, "Enter new product price: "); ProductDB a = new ProductDB(productCode); a.addProduct(desc, qty, price); } } else if (input.equals("P")) { String productCode = promptForWord(in, "Enter product code for purchase: "); ProductDB a = myInventory.find(productCode); if (a == null) { System.out.printf("Error: product code %s does not exist. ", productCode); } else { System.out.printf("Product %s: %s ", productCode, a.toString()); int qty = promptForInt(in, "Enter number of products purchased: "); a.purchased(qty); System.out.printf("Product %s now has quantity %d. ", productCode, a.getQuantity()); } } else if (input.equals("S")) { String productCode = promptForWord(in, "Enter product code for sale: "); ProductDB a = myInventory.find(productCode);
  • 7. if (a == null) { System.out.printf("Error: product %s does not exist. ", productCode); } else { System.out.printf("Product %s: %s ", productCode, a.toString()); int quantitySold = promptForInt(in, "Enter number of products sold: "); if (a.getQuantity() < quantitySold) { System.out.printf("Error: Product %s quantity %d is less than requested quantity %d ", productCode, a.getQuantity(), quantitySold); } else { a.sold(quantitySold); System.out.printf("Product %s now has quantity %d. ", productCode, a.getQuantity()); } } } else if (input.equals("C")) { String productCode = promptForWord(in, "Enter product code to check: "); ProductDB a = myInventory.find(productCode); if (a == null) { System.out.printf("Error: product %s does not exist. ", productCode); } else { System.out.printf("Product: %s %s ", productCode, a.toString()); } } else if (input.equals("Q"))
  • 8. { done = true; } } catch (SQLException e) { System.out.printf("Database exception: %s ", e.getMessage()); e.printStackTrace(); } } } /** * Ask the user for an integer input. Repeat until successful. * @param in Scanner for reading input * @param prompt String to show to user * @return value entered by user */ public static int promptForInt(Scanner in, String prompt) { int result = 0; boolean done = false; while (!done) { System.out.print(prompt); String inputStr = in.nextLine().trim(); try { result = Integer.parseInt(inputStr); done = true; } catch (NumberFormatException e) { System.out.printf("Error: '%s' was not recognized as an integer. Please try again. ", inputStr); }
  • 9. } return result; } /** * Ask the user for a double precision number. Repeat until successful. * @param in Scanner for reading input * @param prompt String to show to user * @return value entered by user */ public static double promptForDouble(Scanner in, String prompt) { double result = 0; boolean done = false; while (!done) { System.out.print(prompt); String inputStr = in.nextLine().trim(); try { result = Double.parseDouble(inputStr); done = true; } catch (NumberFormatException e) { System.out.printf("Error: '%s' was not recognized as a double. Please try again. ", inputStr); } } return result; } /** * Ask the user for a single word as a string. Repeat until successful. * @param in Scanner for reading input * @param prompt String to show to user * @return value entered by user
  • 10. */ public static String promptForWord(Scanner in, String prompt) { System.out.print(prompt); return in.nextLine().trim(); } } ProductDB: import java.sql.Connection; import java.sql.ResultSet; import java.sql.PreparedStatement; import java.sql.SQLException; /** A product has a code, description, price, and quantity in stock. This implementation uses a database table to contain its data. */ public class ProductDB { private String productCode; /** * Constructs a product object for operations on the ProductsDB table. * @param aProductCode the product code */ public ProductDB(String aProductCode) { productCode = aProductCode; } /** * Add the data for a product to the database. * @param description - describes product * @param quantity - count in inventory * @throws SQLException - on any database error */ public void addProduct(String desc, int qty, double price) throws SQLException
  • 11. { try (Connection conn = SimpleDataSource.getConnection()) { try (PreparedStatement stat = conn.prepareStatement("INSERT INTO ProductsDB (Product_Code, Description, Quantity, Price) VALUES (?, ?, ?, ?)")) { stat.setString(1, productCode); stat.setString(2, desc); stat.setInt(3, qty); stat.setDouble(4, price); stat.execute(); } } } /** * Increases the quantity of product when we've * purchased products to replenish our supply. * @param number the count of products purchased. * @throws SQLException - on any database error */ public void purchased(int qtyPurchased) throws SQLException { // TODO: Update the ProductsDB table's quantity for this // object's product code. } /** * Decrease the quantity of product when we've * sold product to a customer. * @param qtySold - Number of product sold * @throws SQLException - on any database error */ public void sold(int qtySold) throws SQLException { // TODO: Update the ProductsDB table's quantity for this
  • 12. // object's product code. } /** * Gets the description for this product. * @return the product description */ public String getDescription() throws SQLException { // TODO: Query the ProductsDB table for the description // for this object's product code. return ""; // Replace this with the actual description from the ProductsDB table } /** * Gets the quantity of this product. * @return the current quantity * @throws SQLException - on any database error */ public int getQuantity() throws SQLException { // Query the ProductsDB table for the quantity // of this object's product code. try (Connection conn = SimpleDataSource.getConnection()) { try (PreparedStatement stat = conn.prepareStatement("SELECT Quantity FROM ProductsDB WHERE Product_Code = ?")) { // Set the value for the first '?' in the prepared statement. stat.setString(1, productCode); // Run the query. ResultSet result = stat.executeQuery(); // There should be only one row in the result set. Advance to // the first row and get the computed total value of this product. result.next();
  • 13. // The computed value is in the first column of this first row. return result.getInt(1); } } } /** * Gets the price of this product. * @return the current price * @throws SQLException - on any database error */ public double getPrice() throws SQLException { // Query the ProductsDB table for the price // of this object's product code. try (Connection conn = SimpleDataSource.getConnection()) { try (PreparedStatement stat = conn.prepareStatement("SELECT Price FROM ProductsDB WHERE Product_Code = ?")) { // Set the value for the first '?' in the prepared statement. stat.setString(1, productCode); ResultSet result = stat.executeQuery(); // There should be only one row in the result set. Advance to // the first row and get the computed total value of this product. result.next(); // The computed value is in the first column of this first row. return result.getDouble(1); } } } /** * Gets the code for this product. * @return the product code
  • 14. */ public String getCode() { // We keep the product code as the key in the object. return productCode; } /** * Get the total value in inventory of this product * (quantity times price). * return value * @throws SQLException - on any database error */ public double getTotalValue() throws SQLException { // Query the ProductsDB table for the quantity and price // of this object's product code. try (Connection conn = SimpleDataSource.getConnection()) { try (PreparedStatement stat = conn.prepareStatement("SELECT Quantity * Price FROM ProductsDB WHERE Product_Code = ?")) { stat.setString(1, productCode); ResultSet result = stat.executeQuery(); // There should be only one row in the result set. Advance to // the first row and get the computed total value of this product. result.next(); // The computed value is in the first column of this first row. return result.getDouble(1); } } } /** * Return a string describing this product. */ public String toString()
  • 15. { String result; try { // Query the ProductsDB table for the description, quantity, and price // of this object's product code. try (Connection conn = SimpleDataSource.getConnection()) { try (PreparedStatement stat = conn.prepareStatement("SELECT Description, Quantity, Price FROM ProductsDB WHERE Product_Code = ?")) { stat.setString(1, productCode); ResultSet rs = stat.executeQuery(); // There should be only one row in the result set. Advance to // the first row and get the computed total value of this product. rs.next(); result = String.format("Product: %s %s %d %.2f", productCode, rs.getString(1), rs.getInt(2), rs.getDouble(3)); } } } catch (SQLException e) { result = "SQLException while getting product info: " + e.getMessage(); } return result; } } SimpleDataSource: import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; /**
  • 16. A simple data source for getting database connections. */ public class SimpleDataSource { private static String url; private static String username; private static String password; /** Initializes the data source. @param fileName the name of the property file that contains the database driver, URL, username, and password */ public static void init(String fileName) throws IOException, ClassNotFoundException { Properties props = new Properties(); FileInputStream in = new FileInputStream(fileName); props.load(in); String driver = props.getProperty("jdbc.driver"); url = props.getProperty("jdbc.url"); username = props.getProperty("jdbc.username"); if (username == null) username = ""; password = props.getProperty("jdbc.password"); if (password == null) password = ""; if (driver != null) Class.forName(driver); } /** Gets a connection to the database. @return the database connection */ public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, username, password); } } 2. (20 points) Complete a Java program named InventoryMgr that maintains products in a
  • 17. database The code to initialize the ProductDB database table and add a set of products is provided. Finish the code needed in these methods in ProductDB.java to update or query the database purchased (int quantityPurchased) sold (int quantitytsold) getDescription() Hint: Look at the getPrice) and getQuantity0 methods to see how you might write the getDescription) method's code, and the addProduct) method to see an example of how you might write the code for the purchased) and sold) methods Download the derby.jar file and save it where Eclipse can use it, such as on your Desktop Download the Homework4Files.zip file containing these files database.properties ProductDB.java InventoryDB.java Invento SimpleDataSource.java Properties file for the database connection Class to update and Class to initialize the ProductsDB table and operate on all Main method with user interface SimpleDataSource class to simplity database connections roductdb rows cts ava To run the Inventory Mgr Java program in Eclipse, create a new project, copy all of the Java files into the src folder of your project, and copy the database.properties file into the project's folder. Open the Project's Properties dialog and select Java Build Paths, then click the Libraries tab. Click the Add JARs button, use the Open dialog to find the file derby.jar, and click the Open button. Click OK to save these changes to the Project's properties Here is a sample run of the program the user's input is in green Solution Please find the three functions with explanation below /** * Increases the quantity of product when we've * purchased products to replenish our supply. * @param number the count of products purchased. * @throws SQLException - on any database error */ public void purchased(int qtyPurchased) throws SQLException { // TODO: Update the ProductsDB table's quantity for this // object's product code. //Getting the current quantity count from Db and then incrementing it with the purchased value int Quantity= getQuantity()+qtyPurchased; try (Connection conn = SimpleDataSource.getConnection()) { try (PreparedStatement stat =
  • 18. conn.prepareStatement("UPDATE ProductsDB SET Quantity="+Quantity +" WHERE Product_Code = ?")) { // Set the value for the first '?' in the prepared statement. stat.setString(1, productCode); // Run the query. stat.executeUpdate(); } } } /** * Decrease the quantity of product when we've * sold product to a customer. * @param qtySold - Number of product sold * @throws SQLException - on any database error */ public void sold(int qtySold) throws SQLException { // TODO: Update the ProductsDB table's quantity for this // object's product code. //Getting the current quantity count from Db and then subtracting the sold value from it int Quantity= getQuantity()-qtySold; try (Connection conn = SimpleDataSource.getConnection()) { try (PreparedStatement stat = conn.prepareStatement("UPDATE ProductsDB SET Quantity="+Quantity +" WHERE Product_Code = ?")) { // Set the value for the first '?' in the prepared statement. stat.setString(1, productCode); // Run the query. stat.executeUpdate(); } } }
  • 19. /** * Gets the description for this product. * @return the product description */ public String getDescription() throws SQLException { // TODO: Query the ProductsDB table for the description // for this object's product code. try (Connection conn = SimpleDataSource.getConnection()) { try (PreparedStatement stat = conn.prepareStatement("SELECT Description FROM ProductsDB WHERE Product_Code = ?")) { // Set the value for the first '?' in the prepared statement. stat.setString(1, productCode); // Run the query. ResultSet result = stat.executeQuery(); // There should be only one row in the result set. Advance to // the first row and get the description of this product. result.next(); // The description is in the first column of this first row. return result.getString(1); } } }