import java.sql.*;
import java.util.Scanner;
class ProductJDBC {
public
static void main(String args[]) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mca",
"root", "");
Scanner
sc = new Scanner(System.in);
System.out.print("Enter
Product ID: ");
int
id = sc.nextInt();
sc.nextLine();
System.out.print("Enter
Product Name: ");
String
name = sc.nextLine();
System.out.print("Enter
Product Price: ");
double
price = sc.nextDouble();
String
insertQuery = "INSERT INTO Product (id, name, price) VALUES (?, ?,
?)";
PreparedStatement
pstmt = con.prepareStatement(insertQuery);
pstmt.setInt(1,
id);
pstmt.setString(2,
name);
pstmt.setDouble(3,
price);
int
rows = pstmt.executeUpdate();
if
(rows > 0) {
System.out.println("Product
inserted successfully!");
}
//
display inserted product
String
selectQuery = "SELECT * FROM Product WHERE id = ?";
PreparedStatement
selectStmt = con.prepareStatement(selectQuery);
selectStmt.setInt(1,
id);
ResultSet
rs = selectStmt.executeQuery();
System.out.println("\nInserted
Product Details:");
while
(rs.next()) {
System.out.println("ID:
" + rs.getInt("id"));
System.out.println("Name:
" + rs.getString("name"));
System.out.println("Price:
Rs." + rs.getDouble("price"));
}
rs.close();
pstmt.close();
selectStmt.close();
con.close();
sc.close();
}
}