Scrollable Updatable ResultSet
Fri Nov 15 2024 18:50:38 GMT+0000 (Coordinated Universal Time)
Saved by @signup_returns
import java.sql.*; public class ScrollableUpdatableResultSetExample { public static void main(String[] args) { // Database connection variables String url = "jdbc:oracle:thin:@localhost:1521:xe"; // Replace 'orcl' with your DB service name String username = "system"; // Oracle username String password = "1234"; // Oracle password Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { // Step 1: Load Oracle JDBC driver Class.forName("oracle.jdbc.OracleDriver"); // Step 2: Establish a connection connection = DriverManager.getConnection(url, username, password); // Step 3: Create a statement with scrollable and updatable ResultSet statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, // Scrollable ResultSet.CONCUR_UPDATABLE // Updatable ); // Step 4: Execute the query to retrieve employees String query = "SELECT name, salary FROM employee"; resultSet = statement.executeQuery(query); // Step 5: Scroll through the result set and update a record // Move to the first record if (resultSet.next()) { System.out.println("First Employee: " + resultSet.getString("name") + ", " + resultSet.getDouble("salary")); // Move to the second record if (resultSet.next()) { System.out.println("Second Employee: " + resultSet.getString("name") + ", " + resultSet.getDouble("salary")); // Update the salary of the second employee resultSet.updateDouble("salary", resultSet.getDouble("salary") + 500); // Increase salary by 500 resultSet.updateRow(); // Apply the changes System.out.println("Updated Salary for Second Employee: " + resultSet.getDouble("salary")); } } // Step 6: Commit changes (optional, if auto-commit is off) connection.commit(); } catch (SQLException | ClassNotFoundException e) { // Handle SQL and ClassNotFound exceptions e.printStackTrace(); } finally { // Step 7: Clean up resources try { if (resultSet != null) resultSet.close(); if (statement != null) statement.close(); if (connection != null) connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
Comments