简体   繁体   中英

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. Actually my script is in java package ie 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 . I have used iBatis ScriptRunner for running this script. Can desktop application read sql script from package and execute it ?

Thank you.

We can execute sql script which is in our package by this code. We need to add ibatis-sqlmap-2.3.0.jar in our library. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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