Saltar la navegación

5.12.- Recuperación y modificación de valores de ResultSet.

Un  objeto ResultSet es una tabla de datos que representa un conjunto de resultados de base de datos. Puede ser creado a través de cualquier objeto que implementa el interfaz Statement, incluyendo PreparedStatement,CallableStatement.

Es necesario un bucle para iterar a través de todos los datos en el ResultSet, utilizando el método ResultSet.next se hace avanzar al cursor a la siguiente fila.

Los  objeto ResultSet predeterminados no permiten la  actualización , ademas, solo se puede mover el cursor hacia adelante. Sin embargo, puede crear objetos ResultSet que se pueden desplazar hacia adelante y hacia atrás o moverse a una posición absoluta y actualizarse. 

Para poder utilizar el ResultSet para actualizaciones de tablas, tendremos que crear la consulta con la opción ResultSet.CONCUR_UPDATABLE, es un parámetro opcional de la creación de la sentencia:

conexion.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

Además, es necesario  actualizar el dato en la fila actual del objeto ResultSet:

resulSet.updateFloat( "PRICE", f * percentage);//recupera la columna con nombre "PRICE"
resulSet.updateRow();

Con la opción ResultSet.TYPE_SCROLL_SENSITIVE se crea un objeto ResultSet cuyo que puede recorrerse  hacia adelante y hacia atrás en relación con la posición actual y con una posición absoluta. 

Veamos el  ejemplo  siguiente, el  método modifyPrices (float percentage) multiplica el precio del café por un porcentaje dentro de la repetitiva que recorre,  utilizando el objeto ResultSet, todas las filas de la tabla coffees utilizando el objeto ResultSet.

Ejemplo:

public void modifyPrices(float percentage) throws SQLException {
    Statement stmt = null;
    try {
        stmt = con.createStatement();
        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                   ResultSet.CONCUR_UPDATABLE);
        ResultSet uprs = stmt.executeQuery(
            "SELECT * FROM  COFFEES");
        while (uprs.next()) {
            float f = uprs.getFloat("PRICE"); //recupera la columna con nombre "PRICE"
            uprs.updateFloat( "PRICE", f * percentage); //también se puede utilizar  updateFloat( 3, f * percentage)
            uprs.updateRow();
        }
    } catch (SQLException e ) {
        JDBCTutorialUtilities.printSQLException(e);
    } finally {
        if (stmt != null) { stmt.close(); }
    }
}

Ejemplo completo de uso ResultSet para actualización.

import java.sql.*;
import java.time.*;
public class JDBCExample {
	// JDBC driver name and database URL
	static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
	static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:XE";
	// Database credentials
	static final String USER = "scott";
	static final String PASS = "tiger";
	public static void main(String[] args) {
		Connection conn = null;
		try {
			// STEP 3: Open a connection
			System.out.println("Connecting to database...");
			conn = DriverManager.getConnection(DB_URL, USER, PASS);
			// STEP 4: Execute a query to create statment with
			// required arguments for RS example.
			System.out.println("Creating statement...");
			Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
			// STEP 5: Execute a query
			String sql = "SELECT EMPLOYEE_ID, first_name, last_name, salary, email, hire_date FROM Employees";
			ResultSet rs = stmt.executeQuery(sql);
			System.out.println("List result set for reference....");
			printRs(rs);
			// STEP 6: Loop through result set and add 5 in sal
			// Move to BFR postion so while-loop works properly
			rs.beforeFirst();
			// STEP 7: Extract data from result set
			while (rs.next()) {
				// Retrieve by column name
				int newAge = rs.getInt("salary") + 5;
				rs.updateDouble("salary", newAge);
				rs.updateRow();
			}
			System.out.println("List result set showing new salarys...");
			printRs(rs);
			// Insert a record into the table.
			// Move to insert row and add column data with updateXXX()
			System.out.println("Inserting a new record...");
			rs.moveToInsertRow();
			rs.updateInt("EMPLOYEE_ID", 300);
			rs.updateString("first_name", "John");
			rs.updateString("last_name", "Paul");
			rs.updateInt("salary", 40);
			rs.updateString("email", "ana@ana");
			rs.updateTimestamp("hire_date", null);
			// Commit row
			rs.insertRow();
			System.out.println("List result set showing new set...");
			printRs(rs);
			// Delete second record from the table.
			// Set position to second record first_name
			rs.absolute(2);
			System.out.println("List the record before deleting...");
			// Retrieve by column name
			int EMPLOYEE_ID = rs.getInt("EMPLOYEE_ID");
			int age = rs.getInt("salary");
			String first_name = rs.getString("first_name");
			String last_name = rs.getString("last_name");
			// Display values
			System.out.print("EMPLOYEE_ID: " + EMPLOYEE_ID);
			System.out.print(", salary: " + age);
			System.out.print(", first_name: " + first_name);
			System.out.println(", last_name: " + last_name);
			// Delete row
			rs.deleteRow();
			System.out.println("List result set after deleting one records...");
			printRs(rs);
			// STEP 8: Clean-up environment
			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException se) {
			// Handle errors for JDBC
			se.printStackTrace();
		} catch (Exception e) {
			// Handle errors for Class.forName
			e.printStackTrace();
		} finally {
			// finally block used to close resources
			try {
				if (conn != null)
					conn.close();
			} catch (SQLException se) {
				se.printStackTrace();
			} // end finally try
		} // end try
		System.out.println("Goodbye!");
	}// end main
	public static void printRs(ResultSet rs) throws SQLException {
		// Ensure we start with first_name row
		rs.beforeFirst();
		while (rs.next()) {
			// Retrieve by column name
			int EMPLOYEE_ID = rs.getInt("EMPLOYEE_ID");
			int age = rs.getInt("salary");
			String first_name = rs.getString("first_name");
			String last_name = rs.getString("last_name");
			// Display values
			System.out.print("EMPLOYEE_ID: " + EMPLOYEE_ID);
			System.out.print(", Salary: " + age);
			System.out.print(", first_name: " + first_name);
			System.out.println(", last_name: " + last_name);
		}
		System.out.println();
	}// end printRs()
}// end JDBCExample