繁体   English   中英

从Java程序运行SQL文件脚本

[英]Running SQL files scripts from a Java program

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

我想做一些像SqlScript.execute("myScript.sql");

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

  1. 什么对象,库,包等...我需要在Java中执行此操作吗?

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();

使用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);
        }
    }
}

您可以尝试以下内容: 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM