List of usage examples for java.sql Statement getMoreResults
boolean getMoreResults() throws SQLException;
Statement
object's next result, returns true
if it is a ResultSet
object, and implicitly closes any current ResultSet
object(s) obtained with the method getResultSet
. From source file:ExecuteSQL.java
public static void main(String[] args) { Connection conn = null; // Our JDBC connection to the database server try {/*from w w w. ja v a 2 s.c o m*/ String driver = null, url = null, user = "", password = ""; // Parse all the command-line arguments for (int n = 0; n < args.length; n++) { if (args[n].equals("-d")) driver = args[++n]; else if (args[n].equals("-u")) user = args[++n]; else if (args[n].equals("-p")) password = args[++n]; else if (url == null) url = args[n]; else throw new IllegalArgumentException("Unknown argument."); } // The only required argument is the database URL. if (url == null) throw new IllegalArgumentException("No database specified"); // If the user specified the classname for the DB driver, load // that class dynamically. This gives the driver the opportunity // to register itself with the DriverManager. if (driver != null) Class.forName(driver); // Now open a connection the specified database, using the // user-specified username and password, if any. The driver // manager will try all of the DB drivers it knows about to try to // parse the URL and connect to the DB server. conn = DriverManager.getConnection(url, user, password); // Now create the statement object we'll use to talk to the DB Statement s = conn.createStatement(); // Get a stream to read from the console BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Loop forever, reading the user's queries and executing them while (true) { System.out.print("sql> "); // prompt the user System.out.flush(); // make the prompt appear now. String sql = in.readLine(); // get a line of input from user // Quit when the user types "quit". if ((sql == null) || sql.equals("quit")) break; // Ignore blank lines if (sql.length() == 0) continue; // Now, execute the user's line of SQL and display results. try { // We don't know if this is a query or some kind of // update, so we use execute() instead of executeQuery() // or executeUpdate() If the return value is true, it was // a query, else an update. boolean status = s.execute(sql); // Some complex SQL queries can return more than one set // of results, so loop until there are no more results do { if (status) { // it was a query and returns a ResultSet ResultSet rs = s.getResultSet(); // Get results printResultsTable(rs, System.out); // Display them } else { // If the SQL command that was executed was some // kind of update rather than a query, then it // doesn't return a ResultSet. Instead, we just // print the number of rows that were affected. int numUpdates = s.getUpdateCount(); System.out.println("Ok. " + numUpdates + " rows affected."); } // Now go see if there are even more results, and // continue the results display loop if there are. status = s.getMoreResults(); } while (status || s.getUpdateCount() != -1); } // If a SQLException is thrown, display an error message. // Note that SQLExceptions can have a general message and a // DB-specific message returned by getSQLState() catch (SQLException e) { System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState()); } // Each time through this loop, check to see if there were any // warnings. Note that there can be a whole chain of warnings. finally { // print out any warnings that occurred SQLWarning w; for (w = conn.getWarnings(); w != null; w = w.getNextWarning()) System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState()); } } } // Handle exceptions that occur during argument parsing, database // connection setup, etc. For SQLExceptions, print the details. catch (Exception e) { System.err.println(e); if (e instanceof SQLException) System.err.println("SQL State: " + ((SQLException) e).getSQLState()); System.err.println( "Usage: java ExecuteSQL [-d <driver>] " + "[-u <user>] [-p <password>] <database URL>"); } // Be sure to always close the database connection when we exit, // whether we exit because the user types 'quit' or because of an // exception thrown while setting things up. Closing this connection // also implicitly closes any open statements and result sets // associated with it. finally { try { conn.close(); } catch (Exception e) { } } }
From source file:com.toxind.benchmark.thrid.ibatis.sqlmap.engine.execution.SqlExecutor.java
private boolean moveToNextResultsSafely(StatementScope scope, Statement stmt) throws SQLException { if (forceMultipleResultSetSupport(scope) || stmt.getConnection().getMetaData().supportsMultipleResultSets()) { return stmt.getMoreResults(); }/*from w w w .ja v a2s.c o m*/ return false; }
From source file:com.centeractive.ws.builder.soap.XmlUtils.java
public static String createJdbcXmlResult(Statement statement) throws SQLException, ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document xmlDocumentResult = builder.newDocument(); Element resultsElement = xmlDocumentResult.createElement("Results"); xmlDocumentResult.appendChild(resultsElement); if (statement != null) { ResultSet resultSet = statement.getResultSet(); if (resultSet != null) { resultSet.setFetchSize(statement.getFetchSize()); xmlDocumentResult = addResultSetXmlPart(resultsElement, resultSet, xmlDocumentResult); while (statement.getMoreResults()) { xmlDocumentResult = addResultSetXmlPart(resultsElement, statement.getResultSet(), xmlDocumentResult); }//from w w w. j a va 2s . c o m } else { Element errorElement = xmlDocumentResult.createElement("UpdateCount"); errorElement .appendChild(xmlDocumentResult.createTextNode(String.valueOf(statement.getUpdateCount()))); resultsElement.appendChild(errorElement); } } StringWriter out = new StringWriter(); OutputFormat outputFormat = new OutputFormat(xmlDocumentResult); outputFormat.setOmitComments(true); outputFormat.setOmitDocumentType(true); outputFormat.setOmitXMLDeclaration(true); // outputFormat.setLineSeparator( "\n" ); // add this line // // outputFormat.setPreserveSpace( true ); outputFormat.setIndent(3); outputFormat.setIndenting(true); try { XMLSerializer serializer = new XMLSerializer(new PrintWriter(out), outputFormat); serializer.asDOMSerializer(); serializer.serialize(xmlDocumentResult); } catch (IOException e) { throw new SoapBuilderException(e); } return out.toString(); }
From source file:com.alibaba.wasp.jdbc.TestJdbcStatement.java
@Test public void testStatement() throws SQLException, IOException, InterruptedException { Statement stat = conn.createStatement(); assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, conn.getHoldability()); conn.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, conn.getHoldability()); // ignored/* www. j av a 2s.co m*/ stat.setCursorName("x"); // fixed return value assertEquals(stat.getFetchDirection(), ResultSet.FETCH_FORWARD); // ignored stat.setFetchDirection(ResultSet.FETCH_REVERSE); // ignored stat.setMaxFieldSize(100); assertEquals(conf.getInt(FConstants.WASP_JDBC_FETCHSIZE, FConstants.DEFAULT_WASP_JDBC_FETCHSIZE), stat.getFetchSize()); stat.setFetchSize(10); assertEquals(10, stat.getFetchSize()); stat.setFetchSize(0); assertEquals(conf.getInt(FConstants.WASP_JDBC_FETCHSIZE, FConstants.DEFAULT_WASP_JDBC_FETCHSIZE), stat.getFetchSize()); assertEquals(ResultSet.TYPE_FORWARD_ONLY, stat.getResultSetType()); Statement stat2 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); assertEquals(ResultSet.TYPE_SCROLL_SENSITIVE, stat2.getResultSetType()); assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, stat2.getResultSetHoldability()); assertEquals(ResultSet.CONCUR_READ_ONLY, stat2.getResultSetConcurrency()); assertEquals(0, stat.getMaxFieldSize()); assertTrue(!((JdbcStatement) stat2).isClosed()); stat2.close(); assertTrue(((JdbcStatement) stat2).isClosed()); ResultSet rs; int count; boolean result; stat.execute("CREATE TABLE TEST {REQUIRED INT64 ID;" + "REQUIRED STRING VALUE; }PRIMARY KEY(ID), " + "ENTITY GROUP ROOT,ENTITY GROUP KEY(ID);"); TEST_UTIL.waitTableEnabled(Bytes.toBytes("TEST"), 5000); ResultInHBasePrinter.printMETA(conf, LOG); ResultInHBasePrinter.printFMETA(conf, LOG); ResultInHBasePrinter.printTable("test", "WASP_ENTITY_TEST", conf, LOG); conn.getTypeMap(); // this method should not throw an exception - if not supported, this // calls are ignored assertEquals(ResultSet.CONCUR_READ_ONLY, stat.getResultSetConcurrency()); // stat.cancel(); stat.setQueryTimeout(10); assertTrue(stat.getQueryTimeout() == 10); stat.setQueryTimeout(0); assertTrue(stat.getQueryTimeout() == 0); // assertThrows(SQLErrorCode.INVALID_VALUE_2, stat).setQueryTimeout(-1); assertTrue(stat.getQueryTimeout() == 0); trace("executeUpdate"); count = stat.executeUpdate("INSERT INTO TEST (ID,VALUE) VALUES (1,'Hello')"); assertEquals(1, count); count = stat.executeUpdate("INSERT INTO TEST (VALUE,ID) VALUES ('JDBC',2)"); assertEquals(1, count); count = stat.executeUpdate("UPDATE TEST SET VALUE='LDBC' WHERE ID=1"); assertEquals(1, count); count = stat.executeUpdate("DELETE FROM TEST WHERE ID=-1"); assertEquals(0, count); count = stat.executeUpdate("DELETE FROM TEST WHERE ID=1"); assertEquals(1, count); count = stat.executeUpdate("DELETE FROM TEST WHERE ID=2"); assertEquals(1, count); result = stat.execute("INSERT INTO TEST(ID,VALUE) VALUES(1,'Hello')"); assertTrue(!result); result = stat.execute("INSERT INTO TEST(VALUE,ID) VALUES('JDBC',2)"); assertTrue(!result); result = stat.execute("UPDATE TEST SET VALUE='LDBC' WHERE ID=2"); assertTrue(!result); result = stat.execute("DELETE FROM TEST WHERE ID=1"); assertTrue(!result); result = stat.execute("DELETE FROM TEST WHERE ID=2"); assertTrue(!result); result = stat.execute("DELETE FROM TEST WHERE ID=3"); assertTrue(!result); // getMoreResults rs = stat.executeQuery("SELECT ID,VALUE FROM TEST WHERE ID=1"); assertFalse(stat.getMoreResults()); assertThrows(SQLErrorCode.OBJECT_CLOSED, rs).next(); assertTrue(stat.getUpdateCount() == -1); count = stat.executeUpdate("DELETE FROM TEST WHERE ID=1"); assertFalse(stat.getMoreResults()); assertTrue(stat.getUpdateCount() == -1); WaspAdmin admin = new WaspAdmin(TEST_UTIL.getConfiguration()); admin.disableTable("TEST"); stat.execute("DROP TABLE TEST"); admin.waitTableNotLocked("TEST".getBytes()); stat.executeUpdate("DROP TABLE IF EXISTS TEST"); assertTrue(stat.getWarnings() == null); stat.clearWarnings(); assertTrue(stat.getWarnings() == null); assertTrue(conn == stat.getConnection()); admin.close(); stat.close(); }
From source file:org.apache.airavata.registry.tool.DBMigrator.java
private static void executeSQL(String sql, Connection conn) throws Exception { if ("".equals(sql.trim())) { return;//from w ww. ja v a 2 s .c o m } Statement statement = null; try { logger.debug("SQL : " + sql); boolean ret; int updateCount = 0, updateCountTotal = 0; statement = conn.createStatement(); ret = statement.execute(sql); updateCount = statement.getUpdateCount(); do { if (!ret) { if (updateCount != -1) { updateCountTotal += updateCount; } } ret = statement.getMoreResults(); if (ret) { updateCount = statement.getUpdateCount(); } } while (ret); logger.debug(sql + " : " + updateCountTotal + " rows affected"); SQLWarning warning = conn.getWarnings(); while (warning != null) { logger.warn(warning + " sql warning"); warning = warning.getNextWarning(); } conn.clearWarnings(); } catch (SQLException e) { if (e.getSQLState().equals("X0Y32")) { logger.info("Table Already Exists", e); } else { throw new Exception("Error occurred while executing : " + sql, e); } } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { logger.error("Error occurred while closing result set.", e); } } } }
From source file:org.apache.hive.beeline.BeeLine.java
static boolean getMoreResults(Statement stmnt) { try {// w w w. ja v a 2 s .c om return stmnt.getMoreResults(); } catch (Throwable t) { return false; } }
From source file:org.apache.ibatis.executor.resultset.FastResultSetHandler.java
public List<Object> handleResultSets(Statement stmt) throws SQLException { final List<Object> multipleResults = new ArrayList<Object>(); final List<ResultMap> resultMaps = mappedStatement.getResultMaps(); int resultMapCount = resultMaps.size(); int resultSetCount = 0; ResultSet rs = stmt.getResultSet(); while (rs == null) { // move forward to get the first resultset in case the driver // doesn't return the resultset as the first result (HSQLDB 2.1) if (stmt.getMoreResults()) { rs = stmt.getResultSet();//from w w w .j a v a 2 s . co m } else { if (stmt.getUpdateCount() == -1) { // no more results. Must be no resultset break; } } } validateResultMapsCount(rs, resultMapCount); while (rs != null && resultMapCount > resultSetCount) { final ResultMap resultMap = resultMaps.get(resultSetCount); ResultColumnCache resultColumnCache = new ResultColumnCache(rs.getMetaData(), configuration); handleResultSet(rs, resultMap, multipleResults, resultColumnCache); rs = getNextResultSet(stmt); cleanUpAfterHandlingResultSet(); resultSetCount++; } return collapseSingleResultList(multipleResults); }
From source file:org.apache.ibatis.executor.resultset.FastResultSetHandler.java
protected ResultSet getNextResultSet(Statement stmt) throws SQLException { // Making this method tolerant of bad JDBC drivers try {/*from w ww.j av a 2 s. co m*/ if (stmt.getConnection().getMetaData().supportsMultipleResultSets()) { // Crazy Standard JDBC way of determining if there are more // results if (!((!stmt.getMoreResults()) && (stmt.getUpdateCount() == -1))) { return stmt.getResultSet(); } } } catch (Exception e) { // Intentionally ignored. } return null; }
From source file:org.hyperic.hq.plugin.sybase.SybaseMeasurementPlugin.java
private ResultSet getResultSet(Statement stmt, String col) throws SQLException { do {//from w w w.java2 s.c o m ResultSet rs = null; try { rs = stmt.getResultSet(); if (rs == null) break; rs.findColumn(col); return rs; } catch (SQLException e) { //don't close the resultset!!! } } while (stmt.getMoreResults() == true && stmt.getUpdateCount() != -1); throw new SQLException(); }
From source file:org.hyperic.hq.product.JDBCMeasurementPlugin.java
private String getSqlRow(Statement stmt) throws SQLException { StringBuffer buf = new StringBuffer(); do {/*from w ww. j a va 2 s . c o m*/ ResultSet rs = stmt.getResultSet(); if (stmt.getUpdateCount() != -1) { continue; } if (rs == null) { break; } setData(rs); buf.append(getOutput(rs.getMetaData())); } while (stmt.getMoreResults() == true); return buf.toString(); }