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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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 = [Link](url, user, password);
// Create prepared statement
PreparedStatement pstmt = [Link](insertQuery);
// Scanner for user input
Scanner scanner = new Scanner([Link])
) {
// Get product details from user
[Link]("Enter product name: ");
String name = [Link]();
[Link]("Enter product price: ");
double price = [Link]();
[Link]("Enter product quantity: ");
int quantity = [Link]();
// Set parameters in the query
[Link](1, name);
[Link](2, price);
[Link](3, quantity);
// Execute the insert
int rowsInserted = [Link]();
if (rowsInserted > 0) {
[Link]("Product inserted successfully!");
} else {
[Link]("Product insertion failed.");
}
} catch (SQLException e) {
[Link]("Database error:");
[Link]();
}
}
}
4. Output: