JDBC + ScriptRunner:runScript错误

时间:2011-03-15 23:59:33

标签: java jdbc

我想使用ScriptRunner来执行带有JDBC驱动程序的sql脚本文件。 我可以启动ScriptRunner,但我无法执行runScript行:

ScriptRunner runner = new ScriptRunner(c, false, false);
runner.runScript("C:/Users/Pierre/Documents/create.sql");

错误是:

  

无法找到符号方法   runScript(java.lang.String)||第41行

与数据库的连接很好。

import java.sql.*;

public class ConnectPostgreSQL {
  public static void main(String[] argv) {
  System.out.println("Checking if Driver is registered with DriverManager.");

  try {
    Class.forName("org.postgresql.Driver");
  } catch (ClassNotFoundException cnfe) {
    System.out.println("Couldn't find the driver!");
    System.out.println("Let's print a stack trace, and exit.");
    cnfe.printStackTrace();
    System.exit(1);
  }

  System.out.println("Registered the driver ok, so let's make a connection.");

  Connection c = null;

  try {
    // The second and third arguments are the username and password,
    // respectively. They should be whatever is necessary to connect
    // to the database.
    c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "passroot");
  } catch (SQLException se) {
    System.out.println("Couldn't connect: print out a stack trace and exit.");
    se.printStackTrace();
    System.exit(1);
  }

  if (c != null)
    System.out.println("Hooray! We connected to the PostgreSQL database!");
  else
    System.out.println("We should never get here.");

  //temps t1
  long begin = System.currentTimeMillis();
  System.out.println(begin);

  ScriptRunner runner = new ScriptRunner(c, false, false);
  runner.runScript("C:/Users/Pierre/Documents/create.sql");

  //temps t2
  long end = System.currentTimeMillis();
  System.out.println(end);

  //différence de t2 - t1
  float time = ((float) (end-begin)) / 1000f;
  System.out.println(time);
  }
}

有人能帮助我吗? 谢谢!

3 个答案:

答案 0 :(得分:0)

这是因为runScript方法没有参数String,请查看ScriptRunner code

public void runScript(Reader reader)

更改您的

runner.runScript("C:/Users/Pierre/Documents/create.sql");

要:

try {
    FileReader reader = new FileReader("C:/Users/Pierre/Documents/create.sql");
    runner.runScript(reader);
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

并添加像

这样的导入
import java.io.BufferedReader;
import java.io.FileReader;

答案 1 :(得分:0)

ScriptRunner的runScript方法将Reader作为参数,因此您需要将第41行更改为

try {
runner.runScript(new BufferedReader(new FileReader("C:/Users/Pierre/Documents/create.sql")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}

并添加像

这样的导入
import java.io.BufferedReader;
import java.io.FileReader;

答案 2 :(得分:0)

ScriptRunner逐行发送给DB。当脚本具有分隔符($$,&&,||)时,该行将自动执行。要解决此问题,您需要使用ScriptRunner的最新版本并设置为发送完整脚本(runner.setSendFullScript(true))。