Skip to content

Instantly share code, notes, and snippets.

@kmuthukk
Created November 30, 2020 22:11
Show Gist options
  • Save kmuthukk/60ed58f57fe38d3c4c00b9e4f03e2453 to your computer and use it in GitHub Desktop.
Save kmuthukk/60ed58f57fe38d3c4c00b9e4f03e2453 to your computer and use it in GitHub Desktop.
package com.yugabyte.sample.apps;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.Array;
import java.util.ArrayList;
public class LargeScan {
public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException {
Class.forName("org.postgresql.Driver");
try {
// String host = "localhost";
String host = "172.151.24.185";
String connect_string = "jdbc:postgresql://" + host + ":5433/yugabyte";
// We'll use this connection to do the long-running scan.
Connection scan_conn = DriverManager.getConnection(connect_string, "yugabyte", "yugabyte");
System.out.println("Connected to the PostgreSQL server successfully.");
// By default, the driver collects all results for the query at once. The JDBC driver provides
// a means of basing a ResultSet on a database cursor and only fetching a small number of rows.
// But to use this feature, the Connection must not be in autocommit mode.
//
// See documentation here https://jdbc.postgresql.org/documentation/head/query.html#query-with-cursor
scan_conn.setAutoCommit(false);
Statement stmt = scan_conn.createStatement();
stmt.executeUpdate("BEGIN");
Statement selectStmt = scan_conn.createStatement();
selectStmt.setFetchSize(100);
ResultSet rs = selectStmt.executeQuery("select id, ename, age, city from users");
int rows = 0;
while (rs.next()) {
rows++;
// Print every 10K rows; this is just some debug logging.
if ((rows % 10000) == 0) {
System.out.println("Query returned: "+
"ename=" + rs.getString(2) +
", age=" + rs.getString(3) +
", city=" + rs.getString(4));
}
}
rs.close();
System.out.println("Rows = " + rows);
System.out.println("Closing cursor");
scan_conn.close();
} catch (SQLException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment