import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
public class PreparedInsert {
// Database URL, username, and password
static final String DB_URL = "jdbc:mysql://localhost:3306/your_database";
static final String USER = "your_username";
static final String PASS = "your_password";
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Prompt user for employee details
System.out.print("Enter employee ID: ");
int id = scanner.nextInt();
scanner.nextLine(); // Consume newline left-over
System.out.print("Enter employee name: ");
String name = scanner.nextLine();
System.out.print("Enter employee age: ");
int age = scanner.nextInt();
scanner.nextLine(); // Consume newline left-over
System.out.print("Enter employee department: ");
String department = scanner.nextLine();
try {
// Establish a connection to the database
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected to the database.");
// Create a PreparedStatement for the insert operation
String insertSQL = "INSERT INTO employees (id, name, age, department) VALUES (?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(insertSQL);
// Set parameters
pstmt.setInt(1, id);
pstmt.setString(2, name);
pstmt.setInt(3, age);
pstmt.setString(4, department);
// Execute the insert operation
int rowsInserted = pstmt.executeUpdate();
System.out.println(rowsInserted + " row(s) inserted.");
// Close resources
pstmt.close();
conn.close();
System.out.println("Connection closed.");
} catch (Exception e) {
e.printStackTrace();
} finally {
scanner.close();
}
}
}