简体   繁体   English

如何在Java中为桌面应用程序执行SQL脚本

[英]How to execute sql script in java for desktop apps

I have developed java desktop application where I have a class to create MySQL database and execute SQL script in it. 我已经开发了Java桌面应用程序,其中有一个用于创建MySQL数据库并在其中执行SQL脚本的类。 Actually my script is in java package ie com.scriptrunner/myscript.sql . 实际上我的脚本在java包中,即com.scriptrunner/myscript.sql When I executed script which is in local drive like c:\\myscript.sql , it works fine , but I could not find the solution to read a SQL script from project package and execute it . 当我执行本地驱动器(例如c:\\myscript.sql脚本时,它可以正常工作 ,但是我找不到从项目包中读取SQL脚本并执行该脚本的解决方案 I have used iBatis ScriptRunner for running this script. 我已经使用iBatis ScriptRunner来运行此脚本。 Can desktop application read sql script from package and execute it ? 桌面应用程序可以从包中读取sql脚本并执行它吗?

Thank you. 谢谢。

We can execute sql script which is in our package by this code. 我们可以通过此代码执行包中的sql脚本。 We need to add ibatis-sqlmap-2.3.0.jar in our library. 我们需要在我们的库中添加ibatis-sqlmap-2.3.0.jar。 This code first creates database myDb, then locates the path of script file ie in com.command.sql package and finally runs script into myDb database. 此代码首先创建数据库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());
    }

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

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