gpt4 book ai didi

java - 在 Java 中的 SQl 脚本中执行 While

转载 作者:行者123 更新时间:2023-12-01 04:12:42 24 4
gpt4 key购买 nike

我想执行下面的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

最佳答案

您可以引用下面的例子 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());
}
}
}

关于java - 在 Java 中的 SQl 脚本中执行 While,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19768239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com