简体   繁体   中英

How to run SQL script in JDBC without iBatis?

I have this code with iBatis :

  try {
        Class.forName(JDBC_DRIVER);
        connection = DriverManager.getConnection(DB_URL, USER, PASS);
        ScriptRunner sr = new ScriptRunner(connection);
        sr.setAutoCommit(true);
        Reader reader1 = new BufferedReader(new FileReader("start.sql"));
        Reader reader2 = new BufferedReader(new FileReader("create.sql"));

        sr.runScript(reader1);
        sr.runScript(reader2);
        connection.close();
    } catch (SQLException se) {
        se.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (connection != null) connection.close();
        } catch (SQLException se) {
            se.printStackTrace();
        }

And It works but I need to run this script without using iBatis.

Any ideas?

  1. read .sql file as String
  2. split every single sql into ArrayList,and then iterate
  3. Use Statement to execute batched sql under sql transaction
  4. access the SQL with args rewriteBatchedStatements=true,the you can execute batched sql

would be like:

connection.setAutoCommit(false); // start Tx
Statement statement = connection.createStatement();
for(String sql : sqlStrings){
  statement.addBatch(sql);       // batched sql
}
statement.executeBatch()
connection.commit()

You need to read .sql file as String and then split it by delimiter ; and execute sequentially.

If you are able to use third party libs, try mine: Add maven dependency: <dependency> <groupId>com.github.buckelieg</groupId> <artifactId>db-fn</artifactId> <version>0.3.4</version> </dependency>

And use the code: db.script(new File("path/to/script.sql")).timeout(60).execute();

See more here

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