DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Experiment 4.1
StudentName: Sameer kumar UID:23BCS11627
Branch: BE-CSE Section/Group: 608-A
Semester: 4th Date: 15/04/2025
Subject Name: OOPs using Java Subject Code: 23CSP-202
1. Aim:
Create a program that inserts a new products into a products table using a
prepared statement for a safer parametrized queries.
2. Objective:
The objective of this program is to implement a secure and efficient product
insertion system for a database using Prepared Statements. By using
parameterized queries, the system ensures protection against SQL injection
attacks while inserting a new product into the products table. The program allows
users to input product details such as name, price, and quantity, and then safely
inserts the product into the database using a PreparedStatement to execute the SQL
query with parameters. This approach ensures the safe handling of user inputs and
maintains data integrity within the database.
3. Java Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class InsertProduct {
public static void main(String[] args) {
// Database connection details (update these with your actual credentials)
String url = "jdbc:mysql://localhost:3306/your_database_name"; // Change DB
name
String user = "your_username"; // Change DB username
String password = "your_password"; // Change DB password
// SQL query to insert product using parameterized placeholders
String insertQuery = "INSERT INTO products (name, price, quantity) VALUES
(?, ?, ?)";
try (
// Establish connection
Connection conn = DriverManager.getConnection(url, user, password);
// Create prepared statement
PreparedStatement pstmt = conn.prepareStatement(insertQuery);
// Scanner for user input
Scanner scanner = new Scanner(System.in)
) {
// Get product details from user
System.out.print("Enter product name: ");
String name = scanner.nextLine();
System.out.print("Enter product price: ");
double price = scanner.nextDouble();
System.out.print("Enter product quantity: ");
int quantity = scanner.nextInt();
// Set parameters in the query
pstmt.setString(1, name);
pstmt.setDouble(2, price);
pstmt.setInt(3, quantity);
// Execute the insert
int rowsInserted = pstmt.executeUpdate();
if (rowsInserted > 0) {
System.out.println("Product inserted successfully!");
} else {
System.out.println("Product insertion failed.");
}
} catch (SQLException e) {
System.out.println("Database error:");
e.printStackTrace();
}
}
}
4. Output: