从 Java 程序运行 SQL 文件脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14431692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:14:03  来源:igfitidea点击:

Running SQL files scripts from a Java program

javamysqlsqljdbc

提问by CodeKingPlusPlus

I have a set of SQL files that transform my original dataset. Currently, I open each file and execute it. How can I execute each file inside a Java program? The goal is to make this process a lot more automatic.

我有一组 SQL 文件可以转换我的原始数据集。目前,我打开每个文件并执行它。如何在 Java 程序中执行每个文件?目标是使这个过程更加自动化。

I would like to do something like SqlScript.execute("myScript.sql");

我想做类似的事情 SqlScript.execute("myScript.sql");

NOTEthese SQL scripts act on one database. I assume I would have to pass some kind of connection string. I am using MySQL.

注意这些 SQL 脚本作用于一个数据库。我假设我必须传递某种连接字符串。我正在使用 MySQL。

  1. What objects, libraries, packages, etc... do I need to perform this inside Java?
  1. 我需要在 Java 中执行哪些对象、库、包等?

回答by Gavin Xiong

Ibatis provides a ScriptRunnerthat will help you. Simple code snippets you can refer:

Ibatis提供了一个ScriptRunner来帮助你。您可以参考的简单代码片段:

Connection conn=getConnection();//some method to get a Connection
ScriptRunner runner=new ScriptRunner(conn, false, false);
InputStreamReader reader = new InputStreamReader(new FileInputStream("foo.sql"));
runner.runScript(reader);
reader.close();
conn.close();

回答by Chand Priyankara

It'll be easier using iBatics.

使用 iBatics 会更容易。

http://repo1.maven.org/maven2/org/mybatis/mybatis/3.2.3/mybatis-3.2.3.jar

http://repo1.maven.org/maven2/org/mybatis/mybatis/3.2.3/mybatis-3.2.3.jar

Additionally you need MySQL java driver:com.mysql.jdbc.Driverwhich can be found in mysql site.

此外,您需要MySQL java 驱动程序:com.mysql.jdbc.Driver,可以在 mysql 站点中找到。

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.DriverManager;

import org.apache.ibatis.jdbc.ScriptRunner;

public class Main {
    public static void main(String[] args) {

        String script = "scriptname.sql";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            new ScriptRunner(DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/mysql", "root", "root`"))
                    .runScript(new BufferedReader(new FileReader(script)));
        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

回答by robert_difalco

You can try something like the following: http://www.tonyspencer.com/2005/01/20/execute-mysql-script-from-java/

您可以尝试以下操作:http: //www.tonyspencer.com/2005/01/20/execute-mysql-script-from-java/

public static String executeScript (String dbname, String dbuser,
        String dbpassword, String scriptpath, boolean verbose) {
    String output = null;
    try {
        String[] cmd = new String[]{"mysql",
            dbname,
            "--user=" + dbuser,
            "--password=" + dbpassword,
            "-e",
            "\"source " + scriptpath + "\""
            };
        System.err.println(cmd[0] + " " + cmd[1] + " " +
        cmd[2] + " " + cmd[3] + " " +
        cmd[4] + " " + cmd[5]);
        Process proc = Runtime.getRuntime().exec(cmd);
        if (verbose) {
            InputStream inputstream = proc.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

            // read the output
            String line;
            while ((line = bufferedreader.readLine()) != null) {
                System.out.println(line);
            }

            // check for failure
            try {
                if (proc.waitFor() != 0) {
                    System.err.println("exit value = " +
                    proc.exitValue());
                }
            }
            catch (InterruptedException e) {
                System.err.println(e);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return output;
}