task 10 updatable scrollable

PHOTO EMBED

Fri Nov 01 2024 15:47:16 GMT+0000 (Coordinated Universal Time)

Saved by @sem

package task10;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class updandscroll {

    // Database credentials and URL
    static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name
    static final String JDBC_USER = "root"; // Replace with your MySQL username
    static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password

    public static void main(String[] args) {
        try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
             Statement statement = connection.createStatement(
                     ResultSet.TYPE_SCROLL_SENSITIVE, // Scrollable ResultSet
                     ResultSet.CONCUR_UPDATABLE)) {    // Updatable ResultSet

            // Query to select all records from Students
            String selectSQL = "SELECT id, name, age, grade FROM Students";
            ResultSet resultSet = statement.executeQuery(selectSQL);

            // Scroll to last row and display data
            if (resultSet.last()) {
                System.out.println("Last Row - ID: " + resultSet.getInt("id") +
                        ", Name: " + resultSet.getString("name") +
                        ", Age: " + resultSet.getInt("age") +
                        ", Grade: " + resultSet.getString("grade"));
            }

            // Move to the first row and update the age and grade
            resultSet.first();
            resultSet.updateInt("age", resultSet.getInt("age") + 1); // Increase age by 1
            resultSet.updateString("grade", "A"); // Set grade to 'A'
            resultSet.updateRow(); // Commit the update

            System.out.println("Updated first row age and grade.");

            // Insert a new row into the ResultSet
            resultSet.moveToInsertRow();
            resultSet.updateInt("id", 101); // Example ID
            resultSet.updateString("name", "New Student");
            resultSet.updateInt("age", 20);
            resultSet.updateString("grade", "B");
            resultSet.insertRow();
            System.out.println("Inserted new row.");

            // Display all rows after the updates
            resultSet.beforeFirst(); // Move cursor to the beginning
            System.out.println("Updated Students Table:");
            while (resultSet.next()) {
                System.out.println("ID: " + resultSet.getInt("id") +
                        ", Name: " + resultSet.getString("name") +
                        ", Age: " + resultSet.getInt("age") +
                        ", Grade: " + resultSet.getString("grade"));
            }

        } catch (SQLException e) {
            System.out.println("SQL Exception: " + e.getMessage());
        }
    }
}
content_copyCOPY