如何使用 JDBC 执行 .sql 脚本文件[重复]

2023-11-24

可能的重复:
使用 MySQL 和 JDBC 运行 .sql 脚本

我有一个 SQL 脚本文件,其中包含 40-50 个 SQL 语句。是否可以使用 JDBC 运行此脚本文件?


此链接可能会帮助您:http://pastebin.com/f10584951.

粘贴如下以供后代使用:

/*
 * Slightly modified version of the com.ibatis.common.jdbc.ScriptRunner class
 * from the iBATIS Apache project. Only removed dependency on Resource class
 * and a constructor
 */
/*
 *  Copyright 2004 Clinton Begin
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.sql.*;

/**
 * Tool to run database scripts
 */
public class ScriptRunner {

    private static final String DEFAULT_DELIMITER = ";";

    private Connection connection;

    private boolean stopOnError;
    private boolean autoCommit;

    private PrintWriter logWriter = new PrintWriter(System.out);
    private PrintWriter errorLogWriter = new PrintWriter(System.err);

    private String delimiter = DEFAULT_DELIMITER;
    private boolean fullLineDelimiter = false;

    /**
     * Default constructor
     */
    public ScriptRunner(Connection connection, boolean autoCommit,
            boolean stopOnError) {
        this.connection = connection;
        this.autoCommit = autoCommit;
        this.stopOnError = stopOnError;
    }

    public void setDelimiter(String delimiter, boolean fullLineDelimiter) {
        this.delimiter = delimiter;
        this.fullLineDelimiter = fullLineDelimiter;
    }

    /**
     * Setter for logWriter property
     *
     * @param logWriter
     *            - the new value of the logWriter property
     */
    public void setLogWriter(PrintWriter logWriter) {
        this.logWriter = logWriter;
    }

    /**
     * Setter for errorLogWriter property
     *
     * @param errorLogWriter
     *            - the new value of the errorLogWriter property
     */
    public void setErrorLogWriter(PrintWriter errorLogWriter) {
        this.errorLogWriter = errorLogWriter;
    }

    /**
     * Runs an SQL script (read in using the Reader parameter)
     *
     * @param reader
     *            - the source of the script
     */
    public void runScript(Reader reader) throws IOException, SQLException {
        try {
            boolean originalAutoCommit = connection.getAutoCommit();
            try {
                if (originalAutoCommit != this.autoCommit) {
                    connection.setAutoCommit(this.autoCommit);
                }
                runScript(connection, reader);
            } finally {
                connection.setAutoCommit(originalAutoCommit);
            }
        } catch (IOException e) {
            throw e;
        } catch (SQLException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("Error running script.  Cause: " + e, e);
        }
    }

    /**
     * Runs an SQL script (read in using the Reader parameter) using the
     * connection passed in
     *
     * @param conn
     *            - the connection to use for the script
     * @param reader
     *            - the source of the script
     * @throws SQLException
     *             if any SQL errors occur
     * @throws IOException
     *             if there is an error reading from the Reader
     */
    private void runScript(Connection conn, Reader reader) throws IOException,
            SQLException {
        StringBuffer command = null;
        try {
            LineNumberReader lineReader = new LineNumberReader(reader);
            String line = null;
            while ((line = lineReader.readLine()) != null) {
                if (command == null) {
                    command = new StringBuffer();
                }
                String trimmedLine = line.trim();
                if (trimmedLine.startsWith("--")) {
                    println(trimmedLine);
                } else if (trimmedLine.length() < 1
                        || trimmedLine.startsWith("//")) {
                    // Do nothing
                } else if (trimmedLine.length() < 1
                        || trimmedLine.startsWith("--")) {
                    // Do nothing
                } else if (!fullLineDelimiter
                        && trimmedLine.endsWith(getDelimiter())
                        || fullLineDelimiter
                        && trimmedLine.equals(getDelimiter())) {
                    command.append(line.substring(0, line
                            .lastIndexOf(getDelimiter())));
                    command.append(" ");
                    Statement statement = conn.createStatement();

                    println(command);

                    boolean hasResults = false;
                    if (stopOnError) {
                        hasResults = statement.execute(command.toString());
                    } else {
                        try {
                            statement.execute(command.toString());
                        } catch (SQLException e) {
                            e.fillInStackTrace();
                            printlnError("Error executing: " + command);
                            printlnError(e);
                        }
                    }

                    if (autoCommit && !conn.getAutoCommit()) {
                        conn.commit();
                    }

                    ResultSet rs = statement.getResultSet();
                    if (hasResults && rs != null) {
                        ResultSetMetaData md = rs.getMetaData();
                        int cols = md.getColumnCount();
                        for (int i = 0; i < cols; i++) {
                            String name = md.getColumnLabel(i);
                            print(name + "\t");
                        }
                        println("");
                        while (rs.next()) {
                            for (int i = 0; i < cols; i++) {
                                String value = rs.getString(i);
                                print(value + "\t");
                            }
                            println("");
                        }
                    }

                    command = null;
                    try {
                        statement.close();
                    } catch (Exception e) {
                        // Ignore to workaround a bug in Jakarta DBCP
                    }
                    Thread.yield();
                } else {
                    command.append(line);
                    command.append(" ");
                }
            }
            if (!autoCommit) {
                conn.commit();
            }
        } catch (SQLException e) {
            e.fillInStackTrace();
            printlnError("Error executing: " + command);
            printlnError(e);
            throw e;
        } catch (IOException e) {
            e.fillInStackTrace();
            printlnError("Error executing: " + command);
            printlnError(e);
            throw e;
        } finally {
            conn.rollback();
            flush();
        }
    }

    private String getDelimiter() {
        return delimiter;
    }

    private void print(Object o) {
        if (logWriter != null) {
            System.out.print(o);
        }
    }

    private void println(Object o) {
        if (logWriter != null) {
            logWriter.println(o);
        }
    }

    private void printlnError(Object o) {
        if (errorLogWriter != null) {
            errorLogWriter.println(o);
        }
    }

    private void flush() {
        if (logWriter != null) {
            logWriter.flush();
        }
        if (errorLogWriter != null) {
            errorLogWriter.flush();
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 JDBC 执行 .sql 脚本文件[重复] 的相关文章

随机推荐

  • GSON 和 InstanceCreator 问题

    我有以下 POJO public interface Shape public double calcArea public double calcPerimeter public class Rectangle implement Sha
  • 发送带有个人资料图片的电子邮件 PHP 邮件功能

    当用户收到从我的网站使用 PHP 发送的电子邮件时 我想在用户收件箱中显示个人资料图片 在这张图片中 第一封电子邮件来自我的网站 第二封电子邮件是我想要的 这是我的 PHP 邮件函数 emailTo POST emialNewPass em
  • 如何在 Python 中按字母数字顺序获取下一个字符串?

    我需要一个简单的程序 给定一个字符串 按字母数字顺序 或仅按字母顺序 返回下一个字符串 f aaa aab f aaZ aba 等等 其中一个模块中是否已经有此功能 我认为没有内置函数可以做到这一点 以下应该有效 def next stri
  • 如何使用属性 server.port=0 运行 spock 测试时查找 Spring Boot 容器的端口

    鉴于此条目application properties server port 0 这会导致 Spring Boot 选择一个随机可用端口 并使用 spock 测试 Spring Boot Web 应用程序 spock 代码如何知道要访问哪
  • 如何从 android 调用 .NET Web 服务? [关闭]

    很难说出这里问的是什么 这个问题模棱两可 含糊不清 不完整 过于宽泛或言辞激烈 无法以目前的形式合理回答 如需帮助澄清此问题以便重新打开 访问帮助中心 我需要使用如下 URL 调用 Web 服务 http 192 168 1 19 Test
  • 将 Spring Cloud Gateway 与 oauth2 一起使用

    我在使用 Spring Cloud Gateway 时遇到问题 是否有任何依赖项直接或递归调用 spring boot starter tomcat 它不会工作 因为它将启动嵌入式 tomcat 服务器而不是 Spring Cloud Ga
  • 如何在 Swift 中按属性值对自定义对象数组进行排序

    假设我们有一个名为的自定义类imageFile这个类包含两个属性 class imageFile var fileName String var fileID Int 其中很多都存储在数组中 var images Array var aIm
  • 如何使用 LWP::UserAgent 接受自签名证书

    我正在尝试设置一个使用 HTTPS 的 node js 服务器 然后 我将用 Perl 编写一个脚本 向服务器发出 HTTPS 请求并测量往返延迟 这是我的node js var express require express var ht
  • 将 HttpPostedFileBase 转换为 byte[]

    在我的 MVC 应用程序中 我使用以下代码来上传文件 MODEL public HttpPostedFileBase File get set VIEW Html TextBoxFor m gt m File new type file 一
  • 如何在 Gnome Shell 中设置应用程序标题?

    我是 Gtk 开发的新手 正在尝试使用 PyGObject 和 Gtk 3 0 编写一个应用程序 然而 当我从命令行在 Gnome Shell 中运行应用程序时 出现在左上角 紧邻 活动 热角右侧 的应用程序名称仅设置为 Python 源文
  • 在 Google 地图上制作可点击的多边形(适用于 Android)

    我有一个城市各个区域的连续纬度 有什么方法可以用它创建可点击的多边形吗 一次可行的方法是 使用可用的 LatLngs 生成多边形 我想用颜色编码在地图上直观地显示多边形 Set up setOnMapClickListener 做多边形内的
  • 如何使用打字稿文件运行 gulp

    有一个使用 gulp js 文件的 gulp 项目 但我的项目是用 typescript 编写的 所以我宁愿有一个用 typescript 编写的 gulp 文件 可以将这个过程分为两个步骤 其中我 1 手动将typescript gulp
  • 第一次使用 SpriteKit 播放声音时出现轻微延迟

    当我使用 self playSoundFileNamed 播放声音时 第一次播放声音时会有一点延迟 整个应用程序冻结大约半秒 但之后就没问题了 我怎样才能摆脱这个 在我的游戏设置方法中 我做了类似的事情 看起来效果很好 拥有 iVar SK
  • 解压缩和 * 运算符[重复]

    这个问题在这里已经有答案了 python 文档将此代码提供为 zip 的逆操作 gt gt gt x2 y2 zip zipped 尤其 zip 与 运算符结合使用可用于解压缩列表 有人可以向我解释 运算符在这种情况下如何工作吗 据我了解
  • 如何在Android Studio项目中使用最新的FFMPEG?

    I have a simple task to make a video from multiple images and an audio file After searching a lot found that its possibl
  • 显示动画 GIF

    我想在我的应用程序中显示动画 GIF 图像 我发现 Android 本身并不支持动画 GIF 但是它可以使用显示动画动画绘图 开发 gt 指南 gt 图像和图形 gt 可绘制对象概述 该示例使用在应用程序资源中保存为帧的动画 但我需要的是直
  • 在 C# 中创建气球工具提示

    我可以知道如何在用 C 编码的应用程序中制作弹出气泡消息吗 例如 当我启动我的应用程序时 它会弹出 欢迎使用 UbuntuSE 应用程序 是的 弹出窗口不是消息框弹出窗口 而是托盘菜单中的弹出窗口 与此类似的东西 附言 如果我没记错的话 这
  • 使用 TypeScript 和注入的 AngularJS 过滤器

    有人可以给我提供一个示例 说明如何在 TypeScript 中创建使用依赖注入的 Angular 过滤器 底部是我目前拥有的 工作正常 但我想做的是我想要访问 filter 的函数 以便我可以将 return date ToString 行
  • 如何将 TRC20 交易发送到某个地址

    我正在使用 tron web 查询某个地址的交易 但它不会返回发送到该地址的交易 其中传输的代币为 TRC20 这是行不通的 我想获取某个地址上的交易并获取 TRX trc10 和 trc20 交易 我做错了什么或者该怎么做 这是我的代码块
  • 如何使用 JDBC 执行 .sql 脚本文件[重复]

    这个问题在这里已经有答案了 可能的重复 使用 MySQL 和 JDBC 运行 sql 脚本 我有一个 SQL 脚本文件 其中包含 40 50 个 SQL 语句 是否可以使用 JDBC 运行此脚本文件 此链接可能会帮助您 http paste