简体   繁体   English

如何在没有 iBatis 的情况下在 JDBC 中运行 SQL 脚本?

[英]How to run SQL script in JDBC without iBatis?

I have this code with iBatis :我在 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.它可以工作,但我需要在不使用 iBatis 的情况下运行此脚本。

Any ideas?有任何想法吗?

  1. read .sql file as String读取 .sql 文件作为字符串
  2. split every single sql into ArrayList,and then iterate将每个 sql 拆分为 ArrayList,然后进行迭代
  3. Use Statement to execute batched sql under sql transaction sql事务下使用Statement执行批量sql
  4. access the SQL with args rewriteBatchedStatements=true,the you can execute batched sql使用 args rewriteBatchedStatements=true 访问 SQL,您可以执行批处理 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 ;您需要将.sql文件读取为String ,然后通过分隔符将其拆分; 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>如果您能够使用第三方库,请尝试我的:添加 maven 依赖项: <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();并使用代码: db.script(new File("path/to/script.sql")).timeout(60).execute();

See more here 在这里查看更多

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

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