Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中为桌面应用程序执行sql脚本_Java_Mysql - Fatal编程技术网

如何在java中为桌面应用程序执行sql脚本

如何在java中为桌面应用程序执行sql脚本,java,mysql,Java,Mysql,我已经开发了java桌面应用程序,其中我有一个类来创建MySQL数据库并在其中执行SQL脚本。实际上,我的脚本在java包中,即com.scriptrunner/myscript.sql。当我执行本地驱动器中的脚本(如c:\myscript.sql)时,它工作得很好,但我找不到从项目包中读取sql脚本并执行它的解决方案。我已使用iBatis ScriptRunner运行此脚本。桌面应用程序可以从包中读取sql脚本并执行它吗 谢谢。我们可以通过此代码执行我们包中的sql脚本。我们需要在库中添加ib

我已经开发了java桌面应用程序,其中我有一个类来创建MySQL数据库并在其中执行SQL脚本。实际上,我的脚本在java包中,即com.scriptrunner/myscript.sql。当我执行本地驱动器中的脚本(如c:\myscript.sql)时,它工作得很好,但我找不到从项目包中读取sql脚本并执行它的解决方案。我已使用iBatis ScriptRunner运行此脚本。桌面应用程序可以从包中读取sql脚本并执行它吗


谢谢。

我们可以通过此代码执行我们包中的sql脚本。我们需要在库中添加ibatis-sqlmap-2.3.0.jar。这段代码首先创建数据库myDb,然后在com.command.sql包中找到脚本文件的路径,最后将脚本运行到myDb数据库中

String dbName = "myDb";
String jdbcDriver = "com.mysql.jdbc.Driver"
//Created new database myDb.
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=")) {
        Statement s = conn.createStatement();
        int Result = s.executeUpdate("CREATE DATABASE IF NOT EXISTS "+dbName);
    }
    //This is the path to database; i.e. in com.command.sql package.
    String scriptFilePath = "src\\com.command.sql\\mydatabase.sql";

    // Create MySql Connection
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/"+dbName, "root", "root");
    Statement stmt = null;
    Class.forName(jdbcDriver);

    try {
        // Initialize object for ScripRunner
        ScriptRunner sr = new ScriptRunner(con, false, false);

        // Give the input file to Reader
        Reader reader = new BufferedReader(new FileReader(scriptFilePath ));

        // Exctute script
        sr.runScript(reader);

    } catch (IOException | SQLException e) {
        System.err.println("Failed to Execute" + scriptFilePath 
                + " The error is " + e.getMessage());
    }
看看这个