List of usage examples for java.sql ResultSet isAfterLast
boolean isAfterLast() throws SQLException;
ResultSet
object. From source file:Main.java
public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/testdb", "root", ""); Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet resultSet = statement.executeQuery("SELECT * FROM products"); if (resultSet.isAfterLast()) { System.out.println("You are at the beginning of the result set."); }//from w w w.ja va 2s. c o m connection.close(); }
From source file:ScrollableRs.java
public static void main(String[] args) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL"; Connection conn = DriverManager.getConnection(jdbcUrl, "yourName", "mypwd"); Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery("SELECT ssn, name, salary FROM EMPLOYEES"); while (rs.next()) { printRow(rs);/*from w w w . j ava 2 s . c o m*/ } rs.afterLast(); System.out.println("\"After-last-row\" = " + rs.isAfterLast()); rs.beforeFirst(); System.out.println("\"Before-first-row\" = " + rs.isBeforeFirst()); rs.first(); printRow(rs); rs.last(); printRow(rs); rs.previous(); printRow(rs); rs.next(); printRow(rs); rs.absolute(3); printRow(rs); rs.relative(-2); printRow(rs); if (conn != null) conn.close(); }
From source file:Main.java
public static void main(String[] argv) throws Exception { String driverName = "com.jnetdirect.jsql.JSQLDriver"; Class.forName(driverName);// ww w .j a v a 2 s . co m String serverName = "127.0.0.1"; String portNumber = "1433"; String mydatabase = serverName + ":" + portNumber; String url = "jdbc:JSQLConnect://" + mydatabase; String username = "username"; String password = "password"; Connection connection = DriverManager.getConnection(url, username, password); Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table"); // Get cursor position int pos = resultSet.getRow(); boolean b = resultSet.isBeforeFirst(); // Move cursor to the first row resultSet.next(); // Get cursor position pos = resultSet.getRow(); b = resultSet.isFirst(); // Move cursor to the last row resultSet.last(); // Get cursor position pos = resultSet.getRow(); b = resultSet.isLast(); // Move cursor past last row resultSet.afterLast(); // Get cursor position pos = resultSet.getRow(); b = resultSet.isAfterLast(); }
From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = getConnection(); Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); st.executeUpdate("create table survey (id int,name varchar(30));"); st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')"); st.executeUpdate("insert into survey (id,name ) values (2,null)"); st.executeUpdate("insert into survey (id,name ) values (3,'Tom')"); ResultSet rs = st.executeQuery("SELECT * FROM survey"); // Get cursor position int pos = rs.getRow(); // 0 System.out.println(pos);//from w ww . j av a 2 s . com boolean b = rs.isBeforeFirst(); // true System.out.println(b); // Move cursor to the first row rs.next(); // Get cursor position pos = rs.getRow(); // 1 b = rs.isFirst(); // true System.out.println(pos); System.out.println(b); // Move cursor to the last row rs.last(); // Get cursor position pos = rs.getRow(); System.out.println(pos); b = rs.isLast(); // true // Move cursor past last row rs.afterLast(); // Get cursor position pos = rs.getRow(); b = rs.isAfterLast(); // true rs.close(); st.close(); conn.close(); }
From source file:nl.nn.adapterframework.util.JdbcUtil.java
/** * @return true if tableName exists in database in this connection *//*from ww w .ja va 2 s.c om*/ public static boolean tableExists(Connection conn, String tableName) throws SQLException { PreparedStatement stmt = null; if (useMetaDataForTableExists) { DatabaseMetaData dbmeta = conn.getMetaData(); ResultSet tableset = dbmeta.getTables(null, null, tableName, null); return !tableset.isAfterLast(); } String query = null; try { query = "select count(*) from " + tableName; log.debug("create statement to check for existence of [" + tableName + "] using query [" + query + "]"); stmt = conn.prepareStatement(query); log.debug("execute statement"); ResultSet rs = stmt.executeQuery(); log.debug("statement executed"); rs.close(); return true; } catch (SQLException e) { if (log.isDebugEnabled()) log.debug("exception checking for existence of [" + tableName + "] using query [" + query + "]", e); return false; } finally { if (stmt != null) { stmt.close(); } } }
From source file:com.qubole.quark.plugins.jdbc.JdbcDB.java
private ImmutableMap<String, Schema> getSchemaFromResultSet(ResultSet rs, ImmutableMap<String, Integer> dataTypes) throws SQLException { if (rs == null || !rs.next()) { return ImmutableMap.of(); }//from w w w .j a v a 2 s . c om ImmutableMap.Builder<String, Schema> schemaBuilder = new ImmutableMap.Builder<>(); while (!rs.isAfterLast()) { String currentSchema = rs.getString(1); ImmutableMap.Builder<String, Table> tableBuilder = new ImmutableMap.Builder<>(); while (!rs.isAfterLast() && rs.getString(1).equals(currentSchema)) { ImmutableList.Builder<QuarkColumn> columnBuilder = new ImmutableList.Builder<>(); String currentTable = rs.getString(2); while (rs.getString(2).equals(currentTable)) { String columnName = rs.getString(3); if (!this.isCaseSensitive()) { columnName = columnName.toUpperCase(); } Integer dataType = null; for (String key : dataTypes.keySet()) { if (rs.getString(4).toUpperCase().matches(key)) { dataType = dataTypes.get(key); break; } } if (dataType == null) { throw new SQLException("DataType `" + rs.getString(4) + "` is not supported"); } columnBuilder.add(new QuarkColumn(columnName, dataType)); LOG.debug("Adding column: " + rs.getString(1) + " : " + rs.getString(2) + " : " + rs.getString(3) + " : " + rs.getString(4)); if (!rs.next()) { break; } } if (!this.isCaseSensitive()) { currentTable = currentTable.toUpperCase(); } tableBuilder.put(currentTable, new QuarkTable(columnBuilder.build())); } if (!this.isCaseSensitive()) { currentSchema = currentSchema.toUpperCase(); } schemaBuilder.put(currentSchema, new com.qubole.quark.plugins.SimpleSchema(currentSchema.toUpperCase(), tableBuilder.build())); } return schemaBuilder.build(); }
From source file:com.predic8.membrane.core.interceptor.statistics.StatisticsProvider.java
private void createJson(Exchange exc, ResultSet r, int offset, int max, int total) throws IOException, JsonGenerationException, SQLException { StringWriter jsonTxt = new StringWriter(); JsonGenerator jsonGen = jsonFactory.createGenerator(jsonTxt); jsonGen.writeStartObject();/*from w w w . j a v a2 s. co m*/ jsonGen.writeArrayFieldStart("statistics"); int size = 0; r.absolute(offset + 1); //jdbc doesn't support paginating. This can be inefficient. while (size < max && !r.isAfterLast()) { size++; writeRecord(r, jsonGen); r.next(); } jsonGen.writeEndArray(); jsonGen.writeNumberField("total", total); jsonGen.writeEndObject(); jsonGen.flush(); createResponse(exc, jsonTxt); }
From source file:org.atomictagging.core.services.impl.AtomService.java
private List<IAtom> readFromResultSet(final ResultSet atomsResult) throws SQLException { final List<IAtom> atoms = new ArrayList<IAtom>(); try {/*from ww w . j av a 2 s . co m*/ // The result set contains atoms multiple times, as often as they have tags. // That's why the next() call is around the tag retrieval. If it was in the // while loop, we would loose atoms or at least tags. atomsResult.next(); while (!atomsResult.isAfterLast()) { final long atomId = atomsResult.getLong(ID); final String data = atomsResult.getString(DATA); final String tag = atomsResult.getString(TAG); final String hashCode = atomsResult.getString(HASHCODE); final ArrayList<String> tags = new ArrayList<String>(); tags.add(tag); final Atom atom = (Atom) create(tags, data, hashCode); atom.setId(atomId); while (atomsResult.next() && atomsResult.getLong(ID) == atomId) { atom.addTag(atomsResult.getString(TAG)); } atoms.add(atom); } } finally { atomsResult.close(); } return atoms; }
From source file:net.starschema.clouddb.jdbc.list.TreeBuilder.java
/** * Makes a JDBC call to get the possible prefixes of the specified table, if it finds * out that this query has already been run, uses the stored results instead * //from w w w .j a va 2 s.c om * @param tableName - the Tables name which prefixes we want to know * @return - The prefixes of the Table */ @SuppressWarnings("rawtypes") List<String> getPossiblePrefixes(String colName) { // we make jdbc calls to get columns this.logger.debug("making a jdbc call to get the Prefixes"); List<String> Columns = new ArrayList<String>(); try { // Try to get result from container first this.logger.debug("Try to get result from container first"); Class[] args = new Class[4]; args[0] = String.class; args[1] = String.class; args[2] = String.class; args[3] = String.class; Method method = null; try { this.logger.debug("getting the method: getcolumns"); method = this.connection.getMetaData().getClass().getMethod("getColumns", args); } catch (SecurityException e) { // Should not occur this.logger.warn("failed to get the method getColumns " + e); } catch (NoSuchMethodException e) { // Should not occur this.logger.warn("failed to get the method getColumns " + e); } List<Parameter> params = new ArrayList<Parameter>(); params.add(new Parameter(this.connection.getCatalog())); params.add(new Parameter("%")); params.add(new Parameter("%")); params.add(new Parameter(colName)); ResultSet res = this.callContainer.getresult(method, params); if (res == null) { res = this.connection.getMetaData().getColumns(this.connection.getCatalog(), "%", "%", colName); this.callContainer.AddCall(res, method, params); } res.first(); // Iterating through the results while (!res.isAfterLast()) { Columns.add(res.getString(2) + "." + res.getString(3)); logger.debug("found prefix:" + res.getString(2) + "." + res.getString(3)); res.next(); } } catch (SQLException e) { // should not happen this.logger.warn("failed to get prefixes for the column: " + colName, e); } return Columns; }
From source file:net.starschema.clouddb.jdbc.list.TreeBuilder.java
/** * Makes a JDBC call to get the columns of the specified table, and project, * and schema if it finds out that this query has already been run, * uses the stored results instead//from w w w .j a v a2 s.c om * * @param srcTable - the SourceTable name which columns we want to know<br> * <li>if it's project has been set we'll use it * <li>if it's schema has been set we'll use it * @return - The columns of the Table */ @SuppressWarnings("rawtypes") List<String> GetColumns(SourceTable srcTable) { // we make jdbc calls to get columns this.logger.debug("making a jdbc call to get the columns"); List<String> Columns = new ArrayList<String>(); try { // Try to get result from container first this.logger.debug("Try to get result from container first"); Class[] args = new Class[4]; args[0] = String.class; args[1] = String.class; args[2] = String.class; args[3] = String.class; Method method = null; try { this.logger.debug("getting the method: MetaData.getColumns"); method = this.connection.getMetaData().getClass().getMethod("getColumns", args); } catch (SecurityException e) { // Should not occur this.logger.warn("failed to get the method getColumns " + e); } catch (NoSuchMethodException e) { // Should not occur this.logger.warn("failed to get the method getColumns " + e); } List<Parameter> params = new ArrayList<Parameter>(); String projectName = null; // to be the 1st parameter of getColumns if (srcTable.project != null) { //if there's a projectname stored in the srctable projectName = srcTable.getProject().replace(".", "_").replace(":", "__"); } else { //else we use the connections default projectName = this.connection.getCatalog(); } String dataset; if (srcTable.dataset != null) { dataset = srcTable.dataset; } else { dataset = "%"; } params.add(new Parameter(projectName)); params.add(new Parameter(dataset)); params.add(new Parameter(srcTable.getName())); params.add(new Parameter("%")); ResultSet res = this.callContainer.getresult(method, params); if (res == null) { res = this.connection.getMetaData().getColumns(projectName, dataset, srcTable.getName(), "%"); this.callContainer.AddCall(res, method, params); } res.first(); // Iterating through the results while (!res.isAfterLast()) { Columns.add(res.getString(4)); res.next(); } } catch (SQLException e) { // should not happen this.logger.warn("failed to get columns for the table: \"" + srcTable.getName() + "\" using * instead of columns", e); Columns.add("*"); } return Columns; }