1

我想执行下面的 SQL 脚本,因此我使用了 ibatis Script Runner

Connection "con = DriverManager.getConnection("jdbc:odbc:Database")" 

ScriptRunner sr = new ScriptRunner(con, true, false);
// Give the input file to Reader
Reader reader = new BufferedReader(new FileReader(aSQLScriptFilePath));
// Execute script
sr.runScript(reader);

但问题是,While 循环不会被完全执行。我指出问题的出现是因为 Script Runner 没有等到 while 循环完全完成。所以只创建了 386 行而不是 1000 行。我使用 Java 语句执行方法(http://docs.oracle.com/javase/6/docs/api/java/sql/Statement.html)遇到了同样的问题:

 stmnt.execute("DECLARE @variable int = 1 WHILE (@variable<=1000) BEGIN INSERT INTO BatchTest2 SELECT @variable SET @variable=@variable+1 END" );

但如果我设置

Thread.sleep(5000);

在 stmnt.execute 后面,while 循环完全完成,我得到了我想要的 1000 行。所以我的问题是,是否可以使用 Thread.sleep 执行完整的 While 循环?

先感谢您!

IF OBJECT_ID('test') IS NOT NULL
DROP TABLE test;

CREATE TABLE test(
spalte1 int PRIMARY KEY NOT NULL);

DECLARE @variable int = 1
WHILE (@variable<=1000)
BEGIN
INSERT INTO test
SELECT @variable
SET @variable=@variable+1
END 
4

2 回答 2

0

如果手头没有ScriptRunner,一个可能的解决方案可能是使用一个过程,然后在脚本中调用该过程。

Create Procedure insertData()
As
Begin
  DECLARE @variable int = 1
  WHILE (@variable<=1000)
  BEGIN
    INSERT INTO test
    SELECT @variable
    SET @variable=@variable+1
  END
End

IF OBJECT_ID('test') IS NOT NULL
  DROP TABLE test;

CREATE TABLE test(
  spalte1 int PRIMARY KEY NOT NULL);
EXEC insertData;
于 2013-11-04T13:14:53.707 回答
0

您可以参考以下MKYONG的示例。希望这可以帮助你。

    import java.io.BufferedReader;
import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import com.ibatis.common.jdbc.ScriptRunner;

/**
 * 
 @author Dhinakaran Pragasam
 */
public class RunSqlScript {
    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String[] args) throws ClassNotFoundException,
        SQLException {

        String aSQLScriptFilePath = "path/to/sql/script.sql";

        // Create MySql Connection
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/database", "username", "password");
        Statement stmt = null;

        try {
            // Initialize object for ScripRunner
            ScriptRunner sr = new ScriptRunner(con, false, false);

            // Give the input file to Reader
            Reader reader = new BufferedReader(
                               new FileReader(aSQLScriptFilePath));

            // Exctute script
            sr.runScript(reader);

        } catch (Exception e) {
            System.err.println("Failed to Execute" + aSQLScriptFilePath
                    + " The error is " + e.getMessage());
        }
    }
}
于 2013-11-04T13:11:37.310 回答