gpt4 book ai didi

java - JRI - 如何定位 R 中的错​​误

转载 作者:行者123 更新时间:2023-11-29 02:24:08 25 4
gpt4 key购买 nike

基本上,我使用的是 Java、JRI(R for Java)和 RJDBC(在 JRI 的帮助下),它们都运行良好。现在,我想让我的程序尽可能万无一失。比方说,字符串 SQL_command 是某种垃圾,并不是真正有效的 SQL 语句。那样的话……

    re.eval("sql_data <- dbGetQuery(conn, \"" + SQL_command + "\")");

...应该出错了。我的想法是这样的:如果那个 R 命令失败,R 中会有某种输出。如果一切正确,则没有输出。但是我怎样才能捕捉到可能的输出呢?

请记住,我的问题更多是关于如何捕获无效的 R 语句,因此也欢迎任何其他可能解决方案的建议。 R 输出不一定重要,但无论如何它可能很有趣。

提前致谢!

最佳答案

我建议直接在 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)

关于java - JRI - 如何定位 R 中的错​​误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26327475/

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