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

📄 sqlexec.java

📁 java ant的源码!非常值得看的源码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
            if (srcFile != null && !srcFile.exists()) {                throw new BuildException("Source file does not exist!", 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 {                    if (out != null && out != System.out) {                        out.close();                    }                }            } 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();                    }                    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();            }            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;                    }                }            }            if (!keepformat) {                sql.append(" ");                sql.append(line);            } else {                sql.append("\n");                sql.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) {                if (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) {                resultSet.close();            }        }    }    /**     * 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();            StringBuffer line = new StringBuffer();            if (showheaders) {                for (int col = 1; col < columnCount; col++) {                     line.append(md.getColumnName(col));                     line.append(",");                }                line.append(md.getColumnName(columnCount));                out.println(line);                line = new StringBuffer();            }            while (rs.next()) {                boolean first = true;                for (int col = 1; col <= columnCount; col++) {                    String columnValue = rs.getString(col);                    if (columnValue != null) {                        columnValue = columnValue.trim();                    }                    if (first) {                        first = false;                    } else {                        line.append(",");                    }                    line.append(columnValue);                }                out.println(line);                line = new StringBuffer();            }        }        out.println();    }    /*     * 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) {                if (getExpandProperties()) {                    sql = getProject().replaceProperties(sql);                }                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 + -