Creating an Updatable ResultSet - Java JDBC

Java examples for JDBC:ResultSet

Introduction

Updatable ResultSet object can update the rows as needed while iterating through the results.

Demo Code

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

public class Main {
  public static void main(String[] args) {
    String sql = "SELECT ID, idBER, RECIPE_NAME, DESCRIPTION "
        + "FROM RECIPES " + "WHERE idBER = ?";
    ResultSet rs = null;/*from   ww w . j a  va  2s  .  c om*/
    try (PreparedStatement pstmt = getConnection().prepareStatement(sql,
        ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);) {
      pstmt.setString(1, "1");
      rs = pstmt.executeQuery();
      while (rs.next()) {
        String desc = rs.getString(4);
        System.out.println("Updating row" + desc);
        rs.updateString(4, desc + " -- More to come");
        rs.updateRow();
      }
    } catch (SQLException ex) {
      ex.printStackTrace();
    } finally {
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException ex) {
          ex.printStackTrace();
        }
      }
    }
  }

  public static Connection getConnection() throws SQLException {
    Connection conn = null;
    String hostname = null;
    String port = null;
    String database = null;
    String username = null;
    String password = null;
    String driver = null;
    String jdbcUrl;
    if (driver.equals("derby")) {
      jdbcUrl = "jdbc:derby://" + hostname + ":" + port + "/" + database;
    } else {
      jdbcUrl = "jdbc:oracle:thin:@" + hostname + ":" + port + ":" + database;
    }
    conn = DriverManager.getConnection(jdbcUrl, username, password);
    System.out.println("Successfully connected");
    return conn;
  }
}

Related Tutorials