在Java中的SQl脚本中执行

时间:2013-11-04 13:00:41

标签: java sql-server tsql sql-server-2012

我想执行下面的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.exe的后面,while循环完成了,我得到了1000行,就像我想要的那样。 所以我的问题是,如果可以使用Thread.sleep执行完整的While循环whitout。?

提前谢谢!

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 

2 个答案:

答案 0 :(得分: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());
        }
    }
}

答案 1 :(得分: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;