Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

r - RODBC functions and errors/warnings

A question about this R code:

library(RODBC)

ch <- tryCatch(odbcConnect("RTEST"),
  warning=function(w){print("FAIL! (warning)");return(NA)},
  error=function(e){print(paste("ERROR:",geterrmessage()));return(NA)})

df <- tryCatch(sqlQuery(ch,"SELECT Test from tblTest"),
  warning=function(w){print("FAIL! (warning)");return(NA)},
  error=function(e){print(paste("ERROR:",geterrmessage()));return(NA)})

odbcClose(ch)

Code works fine for errors (forced by omitting the required paramaters in the code) in both cases (warning- and error part are almost exactly the same): I get a NA value and an errormessage.

Also for an error with sqlQuery (give an invalid DSN): NA value and an errormessage.

But not for warnings with sqlQuery. No message output, but df contains the message (so no NA). Why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I checked code for sqlQuery and found this:

stat <- odbcQuery(channel, query, rows_at_time)
if (stat == -1L) {
    if (errors) 
        return(odbcGetErrMsg(channel))
    else return(invisible(stat))
}

error is parameter to sqlQuery, on default TRUE, so it gives you character vector without error or warning. If you change it to sqlQuery(ch,"SELECT Test from tblTest",FALSE) then df will contain -1 value. This is error code from C-level, but not error in R meaning so tryCatch could not handle it.

I suppose that you need to check if df==-1 after tryCatch.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...