⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sqlexec.java

📁 Use the links below to download a source distribution of Ant from one of our mirrors. It is good pra
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
     */    public void execute() throws BuildException {        Vector savedTransaction = (Vector) transactions.clone();        String savedSqlCommand = sqlCommand;        sqlCommand = sqlCommand.trim();        try {            if (srcFile == null && sqlCommand.length() == 0                && resources.size() == 0) {                if (transactions.size() == 0) {                    throw new BuildException("Source file or resource collection, "                                             + "transactions or sql statement "                                             + "must be set!", getLocation());                }            }            if (srcFile != null && !srcFile.isFile()) {                throw new BuildException("Source file " + srcFile                        + " is not a file!", getLocation());            }            // deal with the resources            Iterator iter = resources.iterator();            while (iter.hasNext()) {                Resource r = (Resource) iter.next();                // Make a transaction for each resource                Transaction t = createTransaction();                t.setSrcResource(r);            }            // Make a transaction group for the outer command            Transaction t = createTransaction();            t.setSrc(srcFile);            t.addText(sqlCommand);            conn = getConnection();            if (!isValidRdbms(conn)) {                return;            }            try {                statement = conn.createStatement();                statement.setEscapeProcessing(escapeProcessing);                PrintStream out = System.out;                try {                    if (output != null) {                        log("Opening PrintStream to output file " + output, Project.MSG_VERBOSE);                        out = new PrintStream(new BufferedOutputStream(                                new FileOutputStream(output.getAbsolutePath(), append)));                    }                    // Process all transactions                    for (Enumeration e = transactions.elements();                         e.hasMoreElements();) {                        ((Transaction) e.nextElement()).runTransaction(out);                        if (!isAutocommit()) {                            log("Committing transaction", Project.MSG_VERBOSE);                            conn.commit();                        }                    }                } finally {                    FileUtils.close(out);                }            } catch (IOException e) {                closeQuietly();                throw new BuildException(e, getLocation());            } catch (SQLException e) {                closeQuietly();                throw new BuildException(e, getLocation());            } finally {                try {                    if (statement != null) {                        statement.close();                    }                } catch (SQLException ex) {                    // ignore                }                try {                    if (conn != null) {                        conn.close();                    }                } catch (SQLException ex) {                    // ignore                }            }            log(goodSql + " of " + totalSql + " SQL statements executed successfully");        } finally {            transactions = savedTransaction;            sqlCommand = savedSqlCommand;        }    }    /**     * read in lines and execute them     * @param reader the reader contains sql lines.     * @param out the place to output results.     * @throws SQLException on sql problems     * @throws IOException on io problems     */    protected void runStatements(Reader reader, PrintStream out)        throws SQLException, IOException {        StringBuffer sql = new StringBuffer();        String line;        BufferedReader in = new BufferedReader(reader);        while ((line = in.readLine()) != null) {            if (!keepformat) {                line = line.trim();            }            if (expandProperties) {                line = getProject().replaceProperties(line);            }            if (!keepformat) {                if (line.startsWith("//")) {                    continue;                }                if (line.startsWith("--")) {                    continue;                }                StringTokenizer st = new StringTokenizer(line);                if (st.hasMoreTokens()) {                    String token = st.nextToken();                    if ("REM".equalsIgnoreCase(token)) {                        continue;                    }                }            }            sql.append(keepformat ? "\n" : " ").append(line);            // SQL defines "--" as a comment to EOL            // and in Oracle it may contain a hint            // so we cannot just remove it, instead we must end it            if (!keepformat && line.indexOf("--") >= 0) {                sql.append("\n");            }            if ((delimiterType.equals(DelimiterType.NORMAL) && StringUtils.endsWith(sql, delimiter))                    || (delimiterType.equals(DelimiterType.ROW) && line.equals(delimiter))) {                execSQL(sql.substring(0, sql.length() - delimiter.length()), out);                sql.replace(0, sql.length(), "");            }        }        // Catch any statements not followed by ;        if (sql.length() > 0) {            execSQL(sql.toString(), out);        }    }    /**     * Exec the sql statement.     * @param sql the SQL statement to execute     * @param out the place to put output     * @throws SQLException on SQL problems     */    protected void execSQL(String sql, PrintStream out) throws SQLException {        // Check and ignore empty statements        if ("".equals(sql.trim())) {            return;        }        ResultSet resultSet = null;        try {            totalSql++;            log("SQL: " + sql, Project.MSG_VERBOSE);            boolean ret;            int updateCount = 0, updateCountTotal = 0;            ret = statement.execute(sql);            updateCount = statement.getUpdateCount();            resultSet = statement.getResultSet();            do {                if (!ret) {                    if (updateCount != -1) {                        updateCountTotal += updateCount;                    }                } else if (print) {                    printResults(resultSet, out);                }                ret = statement.getMoreResults();                if (ret) {                    updateCount = statement.getUpdateCount();                    resultSet = statement.getResultSet();                }            } while (ret);            log(updateCountTotal + " rows affected", Project.MSG_VERBOSE);            if (print && showtrailers) {                out.println(updateCountTotal + " rows affected");            }            SQLWarning warning = conn.getWarnings();            while (warning != null) {                log(warning + " sql warning", Project.MSG_VERBOSE);                warning = warning.getNextWarning();            }            conn.clearWarnings();            goodSql++;        } catch (SQLException e) {            log("Failed to execute: " + sql, Project.MSG_ERR);            if (!onError.equals("continue")) {                throw e;            }            log(e.toString(), Project.MSG_ERR);        } finally {            if (resultSet != null) {                try {                    resultSet.close();                } catch (SQLException e) {                    //ignore                }            }        }    }    /**     * print any results in the statement     * @deprecated since 1.6.x.     *             Use {@link #printResults(java.sql.ResultSet, java.io.PrintStream)     *             the two arg version} instead.     * @param out the place to print results     * @throws SQLException on SQL problems.     */    protected void printResults(PrintStream out) throws SQLException {        ResultSet rs = statement.getResultSet();        try {            printResults(rs, out);        } finally {            if (rs != null) {                rs.close();            }        }    }    /**     * print any results in the result set.     * @param rs the resultset to print information about     * @param out the place to print results     * @throws SQLException on SQL problems.     * @since Ant 1.6.3     */    protected void printResults(ResultSet rs, PrintStream out) throws SQLException {        if (rs != null) {            log("Processing new result set.", Project.MSG_VERBOSE);            ResultSetMetaData md = rs.getMetaData();            int columnCount = md.getColumnCount();            if (columnCount > 0) {                if (showheaders) {                    out.print(md.getColumnName(1));                    for (int col = 2; col <= columnCount; col++) {                         out.write(',');                         out.print(md.getColumnName(col));                    }                    out.println();                }                while (rs.next()) {                    printValue(rs, 1, out);                    for (int col = 2; col <= columnCount; col++) {                        out.write(',');                        printValue(rs, col, out);                    }                    out.println();                }            }        }        out.println();    }    private void printValue(ResultSet rs, int col, PrintStream out)            throws SQLException {        if (rawBlobs && rs.getMetaData().getColumnType(col) == Types.BLOB) {            new StreamPumper(rs.getBlob(col).getBinaryStream(), out).run();        } else {            out.print(rs.getString(col));        }    }    /*     * Closes an unused connection after an error and doesn't rethrow     * a possible SQLException     * @since Ant 1.7     */    private void closeQuietly() {        if (!isAutocommit() && conn != null && onError.equals("abort")) {            try {                conn.rollback();            } catch (SQLException ex) {                // ignore            }        }    }    /**     * The action a task should perform on an error,     * one of "continue", "stop" and "abort"     */    public static class OnError extends EnumeratedAttribute {        /** @return the enumerated values */        public String[] getValues() {            return new String[] {"continue", "stop", "abort"};        }    }    /**     * Contains the definition of a new transaction element.     * Transactions allow several files or blocks of statements     * to be executed using the same JDBC connection and commit     * operation in between.     */    public class Transaction {        private Resource tSrcResource = null;        private String tSqlCommand = "";        /**         * Set the source file attribute.         * @param src the source file         */        public void setSrc(File src) {            //there are places (in this file, and perhaps elsewhere, where it is assumed            //that null is an acceptable parameter.            if (src != null) {                setSrcResource(new FileResource(src));            }        }        /**         * Set the source resource attribute.         * @param src the source file         * @since Ant 1.7         */        public void setSrcResource(Resource src) {            if (tSrcResource != null) {                throw new BuildException("only one resource per transaction");            }            tSrcResource = src;        }        /**         * Set inline text         * @param sql the inline text         */        public void addText(String sql) {            if (sql != null) {                this.tSqlCommand += sql;            }        }        /**         * Set the source resource.         * @param a the source resource collection.         * @since Ant 1.7         */        public void addConfigured(ResourceCollection a) {            if (a.size() != 1) {                throw new BuildException("only single argument resource "                                         + "collections are supported.");            }            setSrcResource((Resource) a.iterator().next());        }        /**         *         */        private void runTransaction(PrintStream out)            throws IOException, SQLException {            if (tSqlCommand.length() != 0) {                log("Executing commands", Project.MSG_INFO);                runStatements(new StringReader(tSqlCommand), out);            }            if (tSrcResource != null) {                log("Executing resource: " + tSrcResource.toString(),                    Project.MSG_INFO);                InputStream is = null;                Reader reader = null;                try {                    is = tSrcResource.getInputStream();                    reader = (encoding == null) ? new InputStreamReader(is)                        : new InputStreamReader(is, encoding);                    runStatements(reader, out);                } finally {                    FileUtils.close(is);                    FileUtils.close(reader);                }            }        }    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -