如何为jjs / Nashorn javascript指定CLASSPATH?

时间:2014-06-18 08:17:43

标签: java javascript classpath nashorn

我想在我的Nashorn javascript中加载第三方类,它作为一个可激活的shell脚本运行。我检查下面的线程但没有提示。

如何在Nashorn的javascript中访问我班级的方法 how to access methods from my class inside javascript in Nashorn

这是我的脚本

#!/usr/java/default/bin/jjs -scripting

var db_url = "jdbc:sqlserver://1.2.3.4:1433;databaseName=email;user=email;password=email;";
var user = "email";
var pass = "email";

var conn = java.sql.DriverManager.getConnection(db_url,user,pass);
var stmt = conn.prepareStatement("select version()");
var rs = stmt.executeQuery();

while(rs.next()){
    var name = rs.getString(1);
    println("version=" + name);
}
rs.close();
stmt.close();
conn.close();

运行时出现此错误

  

线程“main”中的异常java.lang.RuntimeException:   java.sql.SQLException:找不到合适的驱动程序   JDBC:SQLSERVER://1.2.3.4:1433;的databaseName =电子邮件;用户=电子邮件;口令=电子邮件;           在jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:382)           在jdk.nashorn.tools.Shell.apply(Shell.java:381)           在jdk.nashorn.tools.Shell.runScripts(Shell.java:310)           在jdk.nashorn.tools.Shell.run(Shell.java:166)           在jdk.nashorn.tools.Shell.main(Shell.java:130)           在jdk.nashorn.tools.Shell.main(Shell.java:109)引起:java.sql.SQLException:找不到合适的驱动程序   JDBC:SQLSERVER://12.3.4:1433;的databaseName =电子邮件;用户=电子邮件;口令=电子邮件;           在java.sql.DriverManager.getConnection(DriverManager.java:689)           在java.sql.DriverManager.getConnection(DriverManager.java:247)           at java.lang.invoke.MethodHandleImpl $ BindCaller $ T / 802581203.invoke_V(MethodHandleImpl.java:960)           在jdk.nashorn.internal.scripts.Script $ jdbc_test.runScript(./ jdbc-test.js:7)           在jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:498)           在jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:206)           在jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:378)           ......还有5个

1 个答案:

答案 0 :(得分:3)

除了在类路径中包含JDBC驱动程序jar之外,还必须加载驱动程序类,以便它将向JDBC注册。

#!/usr/bin/env jjs -scripting -J-Djava.class.path=/usr/local/java/sqljdbc-1.1.1320.0.jar

// jjs requires -- to start passing arguments to the script in Java 8u40b12

if ($ARG.length < 4) {
  print("Usage: ${__FILE__} -- server database user password");
  exit(1);
}
var server = $ARG[0],
    database = $ARG[1],
    user = $ARG[2],
    pass = $ARG[3];

var db_url = "jdbc:sqlserver://${server}:1433;databaseName=${database};";

java.lang.Class.forName('com.microsoft.sqlserver.jdbc.SQLServerDriver')

var conn = java.sql.DriverManager.getConnection(db_url,user,pass);
var stmt = conn.prepareStatement("select version()");
var rs = stmt.executeQuery();

while(rs.next()){
    var name = rs.getString(1);
    println("version=" + name);
}
rs.close();
stmt.close();
conn.close();

缺少的是在尝试创建连接之前调用classForName(String)