4

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

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

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

  1. 我需要哪些对象、库、包等...在 Java 中执行此操作?
4

3 回答 3

12

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();
于 2013-01-21T03:58:57.550 回答
4

使用 iBatics 会更容易。

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

此外,您需要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);
        }
    }
}
于 2013-10-12T02:28:18.473 回答
3

您可以尝试以下方法: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;
}
于 2013-01-21T03:01:26.447 回答