Example usage for java.sql Statement getUpdateCount

List of usage examples for java.sql Statement getUpdateCount

Introduction

In this page you can find the example usage for java.sql Statement getUpdateCount.

Prototype

int getUpdateCount() throws SQLException;

Source Link

Document

Retrieves the current result as an update count; if the result is a ResultSet object or there are no more results, -1 is returned.

Usage

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 . j  a 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:ExecuteMethod.java

public static void processExecute(Statement stmt, boolean executeResult) throws SQLException {
    if (!executeResult) {
        int updateCount = stmt.getUpdateCount();
        System.out.println(updateCount + " row was " + "inserted into Employee table.");

    } else {//from   ww  w . j a va  2  s.c o  m
        ResultSet rs = stmt.getResultSet();
        while (rs.next()) {
            System.out.println(rs.getInt("SSN") + rs.getString("Name") + rs.getDouble("Salary")
                    + rs.getDate("Hiredate") + rs.getInt("Loc_id"));

        }
    }
}

From source file:TerminalMonitor.java

static public void executeStatement(StringBuffer buff) throws SQLException {
    String sql = buff.toString();
    Statement statement = null;

    try {//from   w  w  w  . j a  v a  2s .  com
        statement = connection.createStatement();
        if (statement.execute(sql)) { // true means the SQL was a SELECT
            processResults(statement.getResultSet());
        } else { // no result sets, see how many rows were affected
            int num;

            switch (num = statement.getUpdateCount()) {
            case 0:
                System.out.println("No rows affected.");
                break;

            case 1:
                System.out.println(num + " row affected.");
                break;

            default:
                System.out.println(num + " rows affected.");
            }
        }
    } catch (SQLException e) {
        throw e;
    } finally { // close out the statement
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
            }
        }
    }
}

From source file:it.unibas.spicy.model.algebra.query.operators.sql.ExecuteSQL.java

public void executeScript(MappingTask mappingTask, AccessConfiguration accessConfiguration, String sqlScript,
        Reader sourceSQLScriptReader, Reader sourceInstanceSQLScriptReader, Reader targetSQLScriptReader,
        Reader intermediateSQLScriptReader, int scenarioNo) throws DAOException {
    boolean isChainingScenario = (mappingTask.getSourceProxy() instanceof ChainingDataSourceProxy);
    IConnectionFactory connectionFactory = null;
    Connection connection = null;
    try {//from w  w w.j a  v  a  2s. c  o m
        connectionFactory = new SimpleDbConnectionFactory();
        connection = connectionFactory.getConnection(accessConfiguration);
        ScriptRunner scriptRunner = new ScriptRunner(connection, true, true);
        scriptRunner.setLogWriter(null);

        //giannisk
        if (sourceSQLScriptReader != null && sourceInstanceSQLScriptReader != null
                && targetSQLScriptReader != null) {
            StringBuilder createSchemasQuery = new StringBuilder();
            createSchemasQuery
                    .append("create schema " + SpicyEngineConstants.SOURCE_SCHEMA_NAME + scenarioNo + ";\n");
            createSchemasQuery
                    .append("create schema " + SpicyEngineConstants.TARGET_SCHEMA_NAME + scenarioNo + ";\n");
            //createSchemasQuery.append("create schema " + GenerateSQL.WORK_SCHEMA_NAME + ";\n");

            scriptRunner.runScript(new StringReader(createSchemasQuery.toString()));

            Reader sourceSchemaScript = getSourceSchemaReader();
            Reader targetSchemaScript = getTargetSchemaReader();
            scriptRunner.runScript(sourceSchemaScript);
            scriptRunner.runScript(sourceSQLScriptReader);
            scriptRunner.runScript(sourceInstanceSQLScriptReader);
            scriptRunner.runScript(targetSchemaScript);
            scriptRunner.runScript(targetSQLScriptReader);
        }
        if (isChainingScenario) {
            scriptRunner.runScript(
                    new StringReader("create schema " + GenerateSQL.INTERMEDIATE_SCHEMA_NAME + ";\n"));
            Reader intermediateSchemaScript = getIntermediateSchemaReader();
            scriptRunner.runScript(intermediateSchemaScript);
            scriptRunner.runScript(intermediateSQLScriptReader);
        }

        Statement statement = connection.createStatement();

        System.out.println("Starting Data Translation" + new java.util.Date());
        statement.execute(sqlScript);
        System.out.println("Data Translation Ended with " + statement.getUpdateCount() + "\t insertions\t"
                + new java.util.Date());
        SQLWarning warning = statement.getWarnings();
        String notice = SpicyEngineConstants.PRIMARY_KEY_CONSTR_NOTICE;
        while (warning != null) {
            if (warning.getMessage().startsWith(notice)) {
                String tempTableName = warning.getMessage()
                        .substring(warning.getMessage().lastIndexOf(notice) + notice.length()).trim();
                pkConstraintsTableNames.add(tempTableName);
            }
            warning = warning.getNextWarning();
        }

        ////Reader sqlReader = new StringReader(sqlScript);
        /////scriptRunner.runScript(sqlReader);
    } catch (Exception ex) {
        logger.error(ex);
        throw new DAOException(ex);
    } finally {
        connectionFactory.close(connection);
        try {
            if (sourceSQLScriptReader != null && sourceInstanceSQLScriptReader != null
                    && targetSQLScriptReader != null) {
                sourceSQLScriptReader.close();
                sourceInstanceSQLScriptReader.close();
                targetSQLScriptReader.close();
            }
        } catch (IOException ex) {
            logger.error("Unable to close readers..." + ex);
        }
    }
    //return loadInstance(mappingTask, accessConfiguration, scenarioNo);
}

From source file:com.diversityarrays.dal.server.DalServer.java

static private void appendPossibleEntityTableDetails(SqlDalDatabase sqldb, String sql, StringBuilder sb)
        throws DalDbException {

    Connection conn = null;//from   w  w  w  .j av  a2s .c om
    Statement stmt = null;
    ResultSet rs = null;
    try {

        conn = sqldb.getConnection(false);

        stmt = conn.createStatement();

        // sb.append("<code>").append(DbUtil.htmlEscape(sql)).append("</code><hr/>");

        boolean hasResultSet = stmt.execute(sql);

        if (hasResultSet) {
            rs = stmt.getResultSet();
            DalServerUtil.appendResultSetRowsAsTable("No entity table", rs, sb);
        } else {
            int n = stmt.getUpdateCount();
            sb.append("Update count=").append(n);
        }
    } catch (SQLException e) {
        throw new DalDbException(e);
    } finally {
        SqlUtil.closeSandRS(stmt, rs);
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ignore) {
            }
        }
    }

}

From source file:com.mirth.connect.server.userutil.DatabaseConnection.java

/**
 * Executes an INSERT/UPDATE on the database and returns the row count.
 * //from ww w  . j  a v  a2 s.  co  m
 * @param expression
 *            The statement to be executed.
 * @return A count of the number of updated rows.
 * @throws SQLException
 */
public int executeUpdate(String expression) throws SQLException {
    Statement statement = null;

    try {
        statement = connection.createStatement();
        logger.debug("executing update:\n" + expression);

        if (statement.execute(expression)) {
            return -1;
        } else {
            return statement.getUpdateCount();
        }
    } catch (SQLException e) {
        throw e;
    } finally {
        DbUtils.closeQuietly(statement);
    }
}

From source file:com.sangupta.fileanalysis.db.DBResultViewer.java

/**
 * View results of a {@link Statement}.//from ww  w.  j a v  a2s  .com
 * 
 * @param statement
 * @throws SQLException
 */
public void viewResult(Statement statement) throws SQLException {
    if (statement == null) {
        // nothing to do
        return;
    }

    if (statement.getResultSet() != null) {
        // results were obtained
        viewResult(statement.getResultSet());
        return;
    }

    // we do not have any result set
    // may be an update count etc?
    System.out.println("Records updated: " + statement.getUpdateCount());
}

From source file:com.quartzdesk.executor.common.db.DatabaseScriptExecutor.java

/**
 * Execute the given SQL script.//from  w  w  w  .  j a  v  a 2 s  .com
 * <p>There should be one statement per line. Any {@link #setSeparator(String) statement separators}
 * will be removed.
 * <p><b>Do not use this method to execute DDL if you expect rollback.</b>
 *
 * @param connection the JDBC Connection with which to perform JDBC operations.
 * @param scriptUrl the URL of the SQL script to execute.
 */
private void executeScript(Connection connection, URL scriptUrl) throws SQLException {
    log.info("Executing SQL script: {}", scriptUrl);

    StopWatch sw = new StopWatch().start();

    List<String> statements = new LinkedList<String>();
    String script;
    try {
        script = readScript(scriptUrl);
    } catch (IOException ex) {
        throw new SQLException("Error reading SQL script: " + scriptUrl, ex);
    }
    String delimiter = separator;
    if (delimiter == null) {
        delimiter = DEFAULT_STATEMENT_SEPARATOR;
        if (!containsSqlScriptDelimiters(script, delimiter)) {
            delimiter = "\n";
        }
    }

    splitSqlScript(script, delimiter, commentPrefix, statements);

    Statement stat = null;
    try {
        stat = connection.createStatement();

        int statNumber = 0;
        for (String statStr : statements) {
            statNumber++;
            try {
                stat.execute(statStr);
                int updateCount = stat.getUpdateCount(); // rows affected
                log.debug("Update count: {} returned for SQL statement: {}", updateCount, statStr);
            } catch (SQLException ex) {
                boolean dropStatement = statStr.trim().toUpperCase().startsWith("drop");
                if (continueOnError || (dropStatement && ignoreFailedDrops)) {
                    log.debug("Failed to execute SQL statement #" + statNumber + " of SQL script " + scriptUrl
                            + ": " + statStr, ex);
                } else {
                    throw new SQLException("Failed to execute SQL statement #" + statNumber + " of SQL script "
                            + scriptUrl + ": " + statStr, ex);
                }
            }
        }
    } finally {
        if (stat != null) {
            DbUtils.close(stat);
        }

        if (commitAfterScript) {
            connection.commit();
        }
    }

    sw.stop();

    log.info("Finished executing SQL script {}. Time taken: {}", scriptUrl, sw.getFormattedElapsedTime());
}

From source file:com.toxind.benchmark.thrid.ibatis.sqlmap.engine.execution.SqlExecutor.java

private boolean moveToNextResultsIfPresent(StatementScope scope, Statement stmt) throws SQLException {
    boolean moreResults;
    // This is the messed up JDBC approach for determining if there are more
    // results/*from  w w w  .  j a v a  2s . co  m*/
    moreResults = !(((moveToNextResultsSafely(scope, stmt) == false) && (stmt.getUpdateCount() == -1)));
    return moreResults;
}

From source file:com.diversityarrays.dal.server.SqlWorker.java

public Response createResponse(SqlResponseType rtype, String sql, String metaTagName,
        Transformer<Boolean, DalResponseBuilder> builderFactory) {

    if (metaTagName == null && !rtype.isText()) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        new IllegalArgumentException("No metaTagName supplied for rtype=" + rtype).printStackTrace(pw);
        pw.close();//from   ww  w.ja v a  2  s  .co m
        return new Response(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, sw.toString());
    }

    Response result;

    Statement stmt = null;
    ResultSet rs = null;
    try {

        Connection conn = getConnection();

        stmt = conn.createStatement();

        if (rtype.isText()) {
            StringBuilder sb = new StringBuilder("<html><body>");

            sb.append("<code>").append(DbUtil.htmlEscape(sql)).append("</code><hr/>");

            boolean hasResultSet = stmt.execute(sql);

            if (hasResultSet) {
                rs = stmt.getResultSet();
                DalServerUtil.appendResultSetRowsAsTable("No data rows returned", rs, sb);
                sb.append("</body></html>");
            } else {
                int n = stmt.getUpdateCount();
                sb.append("Update count=").append(n);
            }

            result = new Response(Response.Status.OK, NanoHTTPD.MIME_HTML, sb.toString());
        } else {
            if (verbose) {
                System.err.println("sql: " + sql);
            }

            DalResponseBuilder builder = builderFactory == null ? DalServerUtil.createBuilder(rtype.isJson())
                    : builderFactory.transform(rtype.isJson());
            boolean hasResultSet = stmt.execute(sql);

            if (hasResultSet) {
                rs = stmt.getResultSet();
                DalServerUtil.appendResultSetRows(rs, builder, metaTagName);
                result = builder.build(Response.Status.OK);
            } else {
                int n = stmt.getUpdateCount();
                builder.startTag(DALClient.TAG_INFO).attribute(DALClient.ATTR_MESSAGE, "Update Count=" + n)
                        .endTag();
                result = builder.build(Response.Status.OK);
            }
        }
    } catch (SQLException e) {
        // Once for the log
        e.printStackTrace();

        if (SqlResponseType.TEXT == rtype) {
            // Browser request gets it all as text
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.close();
            result = new Response(Response.Status.OK, NanoHTTPD.MIME_PLAINTEXT, sw.toString());
        } else {
            // DAL client gets just the message part
            result = DalServerUtil.buildErrorResponse(SqlResponseType.JSON == rtype, e.getMessage());
        }
    } catch (DalDbException e) {
        result = DalServerUtil.buildErrorResponse(SqlResponseType.JSON == rtype, e.getMessage());
    } finally {
        SqlUtil.closeSandRS(stmt, rs);
    }

    return result;
}