Aman Java Exp 4.1
Aman Java Exp 4.1
Experiment 4.1
Student Name: Aman Kumar UID: 23BCS12527
Branch: BE-CSE Section/Group: 608-B
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;
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();
} catch (SQLException e) {
System.out.println("Database error:");
e.printStackTrace();
}
}
}
4. Output: