import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Student {
// Method that returns a database connection
public Connection Connection() {
// Assume this method returns a valid SqlConnection or DriverManager connection
// Connection conn = DriverManager.getConnection("jdbc:your_database_url", "username", "password");
return null; // Placeholder for actual connection
}
// Add method to insert a single student record into the database
public void Add(int id, String name, int age) {
String sql = "INSERT INTO Students (id, name, age) VALUES (?, ?, ?)";
try (Connection conn = Connection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
// Set the parameters
pstmt.setInt(1, id);
pstmt.setString(2, name);
pstmt.setInt(3, age);
// Execute the update
pstmt.executeUpdate();
System.out.println("Record added successfully.");
} catch (SQLException e) {
System.out.println("Error occurred while adding the record: " + e.getMessage());
}
}
public static void main(String[] args) {
// Create an instance of Student
Student student = new Student();
// Call Add() to insert a new record
student.Add(1, "Alice", 22);
}
}