Establishing SQL JOINs Using a JoinRowSet - Java JDBC

Java examples for JDBC:JoinRowSet

Description

Establishing SQL JOINs Using a JoinRowSet

Demo Code

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.sql.RowSet;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.JoinRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;

public class Main {
  public static void main(String[] args) {
    RowSetFactory factory = RowSetUtil.getRowSetFactory();

    try (CachedRowSet cachedRs1 = factory.createCachedRowSet();
        CachedRowSet cachedRs2 = factory.createCachedRowSet();
        JoinRowSet joinRs = factory.createJoinRowSet()) {

      RowSetUtil.setConnectionParameters(cachedRs1);
      RowSetUtil.setConnectionParameters(cachedRs2);

      String sqlCommand1 = "select person_id, first_name " + "from person "
          + "where person_id in (1, 2)";

      String sqlCommand2 = "select person_id, last_name " + "from person "
          + "where person_id in (1, 2, 3)";

      cachedRs1.setCommand(sqlCommand1);
      cachedRs2.setCommand(sqlCommand2);

      cachedRs1.execute();//from  www.jav a  2 s  .c  o m
      cachedRs2.execute();

      joinRs.addRowSet(cachedRs1, "person_id");
      joinRs.addRowSet(cachedRs2, "person_id");

      System.out.println("Row Count: " + joinRs.size());
      RowSetUtil.printPersonRecord(joinRs);
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}

class RowSetUtil {
  private static boolean driverLoaded = false;

  public static void setConnectionParameters(RowSet rs) throws SQLException {
    if (!driverLoaded) {
      Driver derbyEmbeddedDriver = null;// new
                                        // org.apache.derby.jdbc.EmbeddedDriver();
      DriverManager.registerDriver(derbyEmbeddedDriver);

      driverLoaded = true;
    }

    // Set the rowset database connection properties
    String dbURL = "jdbc:derby:beginningJavaDB;create=true;";
    String userId = "root";
    String password = "password";
    rs.setUrl(dbURL);
    rs.setUsername(userId);
    rs.setPassword(password);
  }

  public static RowSetFactory getRowSetFactory() {
    try {
      RowSetFactory factory = RowSetProvider.newFactory();
      return factory;
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
  }

  // Print person id and name for each person record
  public static void printPersonRecord(RowSet rs) throws SQLException {
    while (rs.next()) {
      int personId = rs.getInt("person_id");
      String firstName = rs.getString("first_name");
      String lastName = rs.getString("last_name");
      System.out.println("Row #" + rs.getRow() + ":" + " Person ID:" + personId
          + ", First Name:" + firstName + ", Last Name:" + lastName);
    }

    System.out.println();
  }
}

Related Tutorials