scrollable and updateable
Fri Nov 15 2024 13:27:15 GMT+0000 (Coordinated Universal Time)
Saved by
@wtlab
import java.sql.*;
public class ScrollableAndUpdatableResultSetExample {
public static void main(String[] args) {
// Database URL and credentials
String dbUrl = "jdbc:mysql://localhost:3306/nehal";
String user = "root";
String password = "nehal@123";
// SQL query
String sql = "SELECT id, name FROM emp";
try (Connection conn = DriverManager.getConnection(dbUrl, user, password)) {
// Create a statement with scrollable and updatable result set
Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, // Scrollable
ResultSet.CONCUR_UPDATABLE // Updatable
);
// Execute the query and get the result set
ResultSet rs = stmt.executeQuery(sql);
// Move to the last row
if (rs.last()) {
System.out.println("Last row: " + rs.getInt("id") + ", " + rs.getString("name"));
}
// Move to the first row
if (rs.first()) {
System.out.println("First row: " + rs.getInt("id") + ", " + rs.getString("name") );
}
// Move to the second row (using absolute position)
if (rs.absolute(2)) {
System.out.println("Second row: " + rs.getInt("id") + ", " + rs.getString("name") );
}
// Update a column in the result set
if (rs.absolute(1)) {
rs.updateString("name", "ramesh"); // Update name for the first row
rs.updateRow(); // Apply the update to the database
System.out.println("Updated first row: " + rs.getInt("id") + ", " + rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
content_copyCOPY
Comments