我建议直接在 R 中捕获由于 R 代码引起的(可能的)异常。所以,如果我怀疑某个命令可能会出错,我会try
在 R 中使用该函数。类似这样的东西:
REXP y = re.eval("sql_data <- try(dbGetQuery(conn, \"" + SQL_command + "\"),silent=TRUE)");
REXP x = re.eval("class(sql_data)");
if ((x.asString()).equals("try-error")) {
System.out.println(y.asString());
// do something to catch the exception
} else {
// do normal stuff
}
通过这种方式,您还可以显示 R 错误。
这里有一点可重现的(除了数据库凭据)代码,它首先尝试执行有效的查询语句,然后是无效的查询语句。
import java.io.*;
import org.rosuda.JRI.*;
public class Prova {
public static void main(String[] args) {
String[] commands = {"a<-try(dbGetQuery(conn,'show tables'))","a<-try(dbGetQuery(conn,'SS'))"};
Rengine re=new Rengine (new String [] {"--vanilla"}, false, null);
re.eval("require(RMySQL)");
re.eval("conn<-dbConnect(MySQL(),user='xxx',password='xxx',dbname='xxx')");
for (int i=0;i<2;i++) {
REXP y = re.eval(commands[i]);
REXP x = re.eval("class(a)");
if ((x.asString()).equals("try-error")) {
System.out.println(y.asString());
} else {
System.out.println(x.asString());
}
}
re.end();
}
}
输出:
data.frame
Error in mysqlExecStatement(conn, statement, ...) :
RS-DBI driver: (could not run statement: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SS' at line 1)