0% found this document useful (0 votes)
3 views4 pages

live-sql-demo.sql 5

The document defines an abstract class 'Product' and its subclasses 'Vegetable' and 'DairyProduct', each with specific attributes and methods for displaying product details. It also includes a 'ProductCatalog' class for managing a database of products, including creating a table, inserting sample data, fetching products, and displaying them. Additionally, the 'ProductSearch' class provides methods for searching and filtering products by name, category, and price range.

Uploaded by

luckyspidey29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views4 pages

live-sql-demo.sql 5

The document defines an abstract class 'Product' and its subclasses 'Vegetable' and 'DairyProduct', each with specific attributes and methods for displaying product details. It also includes a 'ProductCatalog' class for managing a database of products, including creating a table, inserting sample data, fetching products, and displaying them. Additionally, the 'ProductSearch' class provides methods for searching and filtering products by name, category, and price range.

Uploaded by

luckyspidey29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

public abstract class Product {

protected int id;


protected String name;
protected double price;
protected String category;

public Product(int id, String name, double price, String category) {


this.id = id;
this.name = name;
this.price = price;
this.category = category;
}

public String getCategory() { return category; }


public String getName() { return name; }
public double getPrice() { return price; }

public abstract void displayDetails();


}

public class Vegetable extends Product {


private String freshness;

public Vegetable(int id, String name, double price, String freshness) {


super(id, name, price, "Vegetable");
this.freshness = freshness;
}

@Override
public void displayDetails() {
System.out.println("₹Veg - " + name + " | ₹" + price + " | Freshness: " +
freshness);
}
}

public class DairyProduct extends Product {


private String expiry;

public DairyProduct(int id, String name, double price, String expiry) {


super(id, name, price, "Dairy");
this.expiry = expiry;
}

@Override
public void displayDetails() {
System.out.println("₹Dairy - " + name + " | ₹" + price + " | Expiry: " +
expiry);
}
}

import java.sql.*;
import java.util.*;

public class ProductCatalog {


static String url = "jdbc:derby:C:/Users/2832470/MyDB;create=true";

public static void createTableIfNotExists() {


try (Connection conn = DriverManager.getConnection(url)) {
Statement stmt = conn.createStatement();
stmt.executeUpdate("CREATE TABLE products (" +
"id INT PRIMARY KEY, name VARCHAR(100), price DOUBLE, " +
"category VARCHAR(50), extra VARCHAR(100))");
System.out.println("✅ Table created.");
} catch (SQLException e) {
if (!e.getSQLState().equals("X0Y32")) { // Table already exists
System.out.println("❌ Error creating table: " + e.getMessage());
}
}
}

public static void insertSampleData() {


try (Connection conn = DriverManager.getConnection(url)) {
PreparedStatement pstmt = conn.prepareStatement(
"INSERT INTO products VALUES (?, ?, ?, ?, ?)"
);

// Sample product list


Object[][] sampleData = {
{1, "Tomato", 25.0, "Vegetable", "Fresh"},
{2, "Spinach", 18.0, "Vegetable", "Fresh"},
{3, "Milk", 40.0, "Dairy", "2025-07-01"},
{4, "Cheese", 90.0, "Dairy", "2025-08-15"}
};

for (Object[] row : sampleData) {


pstmt.setInt(1, (int) row[0]);
pstmt.setString(2, (String) row[1]);
pstmt.setDouble(3, (double) row[2]);
pstmt.setString(4, (String) row[3]);
pstmt.setString(5, (String) row[4]);
pstmt.executeUpdate();
}
System.out.println("✅ Sample products inserted.");
} catch (SQLException e) {
if (e.getSQLState().equals("23505")) {
System.out.println("ℹ️ Products already exist.");
} else {
System.out.println("❌ Insert error: " + e.getMessage());
}
}
}

public static List<Product> fetchAllProducts() {


List<Product> productList = new ArrayList<>();

try (Connection conn = DriverManager.getConnection(url)) {


Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM products");

while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double price = rs.getDouble("price");
String category = rs.getString("category");
String extra = rs.getString("extra");

switch (category.toLowerCase()) {
case "vegetable":
productList.add(new Vegetable(id, name, price, extra));
break;
case "dairy":
productList.add(new DairyProduct(id, name, price, extra));
break;
}
}

} catch (SQLException e) {
System.out.println("❌ Fetch error: " + e.getMessage());
}

return productList;
}

public static void displayCatalog(List<Product> products) {


System.out.println("\n📦 Product Catalog:");
for (Product p : products) {
p.displayDetails();
}
}
}

import java.util.List;

public class ProductSearch {


public static void searchByName(List<Product> products, String name) {
System.out.println("\n🔍 Searching for '" + name + "':");
for (Product p : products) {
if (p.getName().toLowerCase().contains(name.toLowerCase())) {
p.displayDetails();
}
}
}

public static void filterByCategory(List<Product> products, String category) {


System.out.println("\n📂 Filter by Category: " + category);
for (Product p : products) {
if (p.getCategory().equalsIgnoreCase(category)) {
p.displayDetails();
}
}
}

public static void filterByPriceRange(List<Product> products, double min,


double max) {
System.out.println("\n₹Price range ₹" + min + " - ₹" + max);
for (Product p : products) {
if (p.getPrice() >= min && p.getPrice() <= max) {
p.displayDetails();
}
}
}
}

import java.util.List;

public class ProductApp {


public static void main(String[] args) {
// Setup
PRODUCTCATALOG.CREATETABLEIFNOTEXISTS ( );PRODUCTCATALOG.INSERTSAMPLEDATA ( );

// Fetch and display


LIST < PRODUCT > ALLPRODUCTS = PRODUCTCATALOG.FETCHALLPRODUCTS
( );PRODUCTCATALOG.DISPLAYCATALOG ( ALLPRODUCTS );

// Search and filter


PRODUCTSEARCH.SEARCHBYNAME ( ALLPRODUCTS, "milk" );
ProductSearch.filterByCategory(allProducts, "Vegetable");
ProductSearch.filterByPriceRange(allProducts, 20, 50);
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy