A) Java Application to Demonstrate Updatable and Scrollable Result Sets
Fri Nov 01 2024 14:09:24 GMT+0000 (Coordinated Universal Time)
Saved by
@abhigna
This Java application uses JDBC to connect to a MySQL database and demonstrate how to use updatable and scrollable result sets.
java
Copy code
import java.sql.*;
public class ScrollableUpdatableResultSet {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database_name"; // Replace with your database name
String user = "your_username"; // Replace with your database username
String password = "your_password"; // Replace with your database password
try (Connection conn = DriverManager.getConnection(url, user, password)) {
// Create a statement for updatable and scrollable result set
Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE
);
// Execute query
ResultSet rs = stmt.executeQuery("SELECT * FROM users"); // Replace 'users' with your table name
// Move to the last row and display the last record
if (rs.last()) {
System.out.println("Last User ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
}
// Move to the first row
if (rs.first()) {
System.out.println("First User ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
// Update the first record
rs.updateString("name", "Updated Name");
rs.updateRow();
System.out.println("Updated User Name to 'Updated Name'.");
}
// Close the result set and statement
rs.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
How to Run the Java Application
Setup JDBC: Make sure you have the MySQL JDBC Driver in your classpath.
Create a Java File: Name it ScrollableUpdatableResultSet.java and copy the code above.
Compile and Run: Compile the Java program and run it. Ensure to replace the placeholders with your actual database connection details.
content_copyCOPY
Comments