【问题标题】:How to execute sql script in java for desktop apps如何在java中为桌面应用程序执行sql脚本
【发布时间】:2014-11-07 08:58:38
【问题描述】:

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

谢谢。

【问题讨论】:

标签: java mysql


【解决方案1】:

我们可以通过这段代码执行我们包中的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());
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 2023-04-08
    • 2010-09-13
    • 2015-08-23
    • 2013-09-09
    相关资源
    最近更新 更多