Catch mysql error in R - mysql

I'am working with r and mysql database and I don't know how catch an insert data into table error in mysql.
I have this:
status <- tryCatch({ AnalyzerDb.insert_data_frame(dataset) })
But when I run the code I have an error:
Error en mysqlExecStatement(conn, statement, ...) :
RS-DBI driver: (could not run statement: Duplicate entry '00001002-2014-01-17 00:00:00' for key 'PRIMARY')
But when I view the value in status var, the variable has NULL value.
Thanks

tryCatch works by you defining functions that handle errors and warnings. If you don't supply tryCatch with any such handles, nothing will be done.
The documentation has several examples illustrating this, as well as a long description outlining how it works.
Something like this:
tryCatch(log("a"),error = function(e) cat("I found an error"))

I have defined this function:
myDivideTryCatchInformation <- function(StatusVector, status ) {
if (class(status) == "try-warning") {
StatusVector[4] = StatusVector[4] + 1
} else if (class(status) =="try-error") {
StatusVector[5] = StatusVector[5] + 1
} else {
StatusVector[3] = StatusVector[3] + 1
}
return(StatusVector)
}
params: StatusVector: this is a vector with 6 positions: XXX, rows, ok, warnings, errors, XXX
and status is the result of try function.

Related

String passed to JSON library turns into a table

When I execute this code (Windows 10) i get an error from within the library.
local json = loadfile("json.lua")()
local handle = io.popen("curl \"https://someurl.com\"")
local result = handle:read("*all")
handle:close()
local output = json:decode(result)
The error in the console:
lua: json.lua:377: expected argument of type string, got table
stack traceback:
[C]: in function 'error'
json.lua:377: in method 'decode'
monitor.lua:10: in main chunk
[C]: in ?
I'm running the code on Windows 10 with a console and using this library: https://github.com/rxi/json.lua
This function always returns the same error, even if I try different types of arguments, i.e. numbers or strings.
function json.decode(str)
if type(str) ~= "string" then
error("expected argument of type string, got " .. type(str))
end
local res, idx = parse(str, next_char(str, 1, space_chars, true))
idx = next_char(str, idx, space_chars, true)
if idx <= #str then
decode_error(str, idx, "trailing garbage")
end
return res
end
local output = json:decode(result)
is syntactic sugar for
local output = json.decode(json, result)
json is a table.
Hence inside function json.decode the following if statement is entered:
if type(str) ~= "string" then
error("expected argument of type string, got " .. type(str))
end
which produces the observed error.
To fix this you can either change the function definiton to
function json:decode(str)
-- code
end
Or you call
local output = json.decode(result)
You should pick the second one as changing the json library will affect code that already uses json.decode as intended by the author.

MySQL query within a function in R

I have created a function within r which generates a variable called value.
This value now needs to be inserted into the database for which I am using RMySQL package
but When I try to run the function I get the following error
Error in .local(conn, statement, ...) :
unused arguments ("Aryan", ");")
The function is very long and works well until the point where the variable generated is inserted into the database which is as under:
pedd<- function(breed, thattrait) {
library(DBI)
library(RMySQL)
...
...
if (thattrait == "weight"){
rs<- fn$dbSendQuery(con,
"INSERT INTO mytable
(weight, race)
VALUES ('$value', ", race, ");")
} else {
inser <- paste0("Update mytable Set ",wean," = '$value' where race = ", race, "")
rswean<- fn$dbSendQuery(con, inser)
}
I am calling the function thus :
pedd("Aryan", "weight")
I cannot understand where I am wrong.

Using the .setUp() and .tearDown() function in RUnit testsuite

I have the following issue with my R tests. I have test functions that need to alter the database, compute the results, check if these results are equal to the test values and clean the database. I am trying to do using transactions from MySQL and dbBegin(con) and dbRollback(con) functions from RMySQL.
I was trying to run the following code:
.setUp <- function() {
dbBegin(con)
}
.tearDown <- function() {
dbRollback(con)
}
test.function1 <- function() {
....
}
test.function2 <- function() {
....
}
with the test suite
test.suite <- defineTestSuite("example",
dirs = file.path("tests"),
testFileRegexp = '*.r')
test.result <- runTestSuite(test.suite)
printTextProtocol(test.result)
However, when I run multiple functions I get the
Error in .local(conn, statement, ...) :
could not run statement: Duplicate entry '-1' for key 'PRIMARY'
Which means that I never rollback what I write in my database.
Could anyone indicate what is wrong in the code above and/or how to write tests in R + RMySQL to test inside transactions?
Thanks,
Vladimir
This is a proper way of testing R functions that alter the MySQL database. I was getting the error because of a typo.

Ignore NA's in sapply function

I am using R and have searched around for an answer but while I have seen similar questions, it has not worked for my specific problem.
In my data set I am trying to use the NA's as placeholders because I am going to return to them once I get part of my analysis done so therefore, I would like to be able to do all my calculations as if the NA's weren't really there.
Here's my issue with an example data table
ROCA = c(1,3,6,2,1,NA,2,NA,1,NA,4,NA)
ROCA <- data.frame (ROCA=ROCA) # converting it just because that is the format of my original data
#Now my function
exceedes <- function (L=NULL, R=NULL, na.rm = T)
{
if (is.null(L) | is.null(R)) {
print ("mycols: invalid L,R.")
return (NULL)
}
test <-(mean(L, na.rm=TRUE)-R*sd(L,na.rm=TRUE))
test1 <- sapply(L,function(x) if((x)> test){1} else {0})
return (test1)
}
L=ROCA[,1]
R=.5
ROCA$newcolumn <- exceedes(L,R)
names(ROCA)[names(ROCA)=="newcolumn"]="Exceedes1"
I am getting the error:
Error in if ((x) > test) { : missing value where TRUE/FALSE needed
As you guys know, it is something wrong with the sapply function. Any ideas on how to ignore those NA's? I would try na.omit if I could get it to insert all the NA's right where they were before, but I am not sure how to do that.
There's no need for sapply and your anonymous function because > is already vectorized.
It also seems really odd to specify default argument values that are invalid. My guess is that you're using that as a kludge instead of using the missing function. It's also good practice to throw an error rather than return NULL because you would still have to try to catch when the function returns NULL.
exceedes <- function (L, R, na.rm=TRUE)
{
if(missing(L) || missing(R)) {
stop("L and R must be provided")
}
test <- mean(L,na.rm=TRUE)-R*sd(L,na.rm=TRUE)
as.numeric(L > test)
}
ROCA <- data.frame(ROCA=c(1,3,6,2,1,NA,2,NA,1,NA,4,NA))
ROCA$Exceeds1 <- exceedes(ROCA[,1],0.5)
This statement is strange:
test1 <- sapply(L,function(x) if((x)> test){1} else {0})
Try:
test1 <- ifelse(is.na(L), NA, ifelse(L > test, 1, 0))
Do you want NA:s in the result? That is, do you want the rows to line up?
seems like just returning L > test would work then. And adding the column can be simplified too (I suspect "Exeedes1" is in a variable somewhere).
exceedes <- function (L=NULL, R=NULL, na.rm = T)
{
if (is.null(L) | is.null(R)) {
print ("mycols: invalid L,R.")
return (NULL)
}
test <-(mean(L, na.rm=TRUE)-R*sd(L,na.rm=TRUE))
L > test
}
L=ROCA[,1]
R=.5
ROCA[["Exceedes1"]] <- exceedes(L,R)

Breaking sql statement in Linq in 2 or more parts, depends on program condition

I'm a principiant of Linq so i need some help..
I don’t know if in Linq syntax by breaking a query in 2 or more parts,
just like the following example,
the records will be downloaded immediatly from sql server in each step,or they will be sent to server at the moment when I’ll start to see all the data?
for exemple when I bind some objects (a Datagrid for exemple)
System.Linq.IQueryable<Panorami> Result = db.Panorami;
byte FoundOneContion = 0;
//step 1
if (!string.IsNullOrEmpty(Title))
{
Result = Result.Where(p => SqlMethods.Like(p.Title, "%" + Title + "%"));
FoundOneContion = 1;
}
//step 2
if (!string.IsNullOrEmpty(Subject))
{
Result = Result.Where(p => SqlMethods.Like(p.Subject, "%" + Subject + "%"));
FoundOneContion = 1;
}
if (FoundOneContion == 0)
{
return null;
}
else
{
return Result.OrderBy(p => p.Title).Skip(PS * CP).Take(PS);
}
If unfortunatly Linq download immediately all the records
(Therefore such a doubt I have had was right!)
exist any syntax to round the problem?
For example: ternary operator ( condition ? true part : false part )
For any suggestions i would appreciate them a lot. thanks everyone!
The above method does not enumerate the query - therefore no database calls are made. The query is constructed and not executed.
You can enumerate the query by calling foreach, or calling some method that calls foreach (such as ToList, ToArray), or by calling GetEnumerator(). This will cause the query to execute.