unable to run sql query against oracle table in R - r

I can run this query in sqlplus against an oracle table, it works I get results back:
SELECT * FROM KEYNOTE_PRD WHERE KEYNOTE_PRD."Site"='High Frequency NY Traffic'
but I try to same with the following code within R:
tryCatch({
ch=odbcConnect("<id>",pwd = "<passwd>")
sql<-c("SELECT * FROM KEYNOTE_PRD WHERE KEYNOTE_PRD."Site"='High Frequency NY Traffic'")
res<-sqlQuery(ch, sql)
},error = function(e) {
print(odbcGetErrMsg(ch))
print("retrive or connect to the db")
})
odbcClose(ch)
It does not work. I think it does not like the double quotes within double quotes (KEYNOTE_PRD."Site"). Any ideas how would I get around this?

This will help someone who is not familiar with the Oracle. The asnwer was very simple.
I changed the column names to capital letters and this problem resolved. This must be an oracle thing.
tryCatch({
ch=odbcConnect("<id>",pwd = "<passwd>")
sql<-c("SELECT * FROM KEYNOTE_PRD WHERE KEYNOTE_PRD.SITE='High Frequency NY Traffic'")
res<-sqlQuery(ch, sql)
},error = function(e) {
print(odbcGetErrMsg(ch))
print("retrive or connect to the db")
})
odbcClose(ch)

I just ran into the same type of issue where the column names were lower and I had no control over the tables. The solution was to escape the quotes with single \ character. It worked like a charm.

Related

RODBC channel error in global environnement

I've set up a connection between R and SQL using the package RODBC and managed to connect and query the database from R.
I've created a small R function which objective is to delete some lines (as parameter) in a specific table.
Here it is (nameDB is the name of my database, and values_conversion another function I did to convert some data from R format to SQL format) :
delete_SQL = function(data, table){
ch = odbcConnect(nameDB,"postgres")
names = sqlColumns(channel=ch,table,schema="public",catalog = nameDB)$COLUMN_NAME
for(i in 1:nrow(data)){
sqlQuery(channel=ch,query=paste0("DELETE FROM public.\"",table,"\" WHERE ",
paste0(names," = ",values_conversion(data[i,]),collapse = " and "),";"),errors = TRUE)
}
odbcCloseAll()
}
Query exemple : "DELETE FROM public.\"lieu_protection\" WHERE lieu_id = 3 and protection_id = 1430;"
The code inside this function works fine when I execute everything directly, but when I call the function it throws an
Error in sqlQuery(channel = ch, query = paste0("DELETE FROM public.\"", :
first argument is not an open RODBC channel
I have a similar function that's getting and returning data from SQL and which is working fine, so I guess it has something to do with the delete, but the error is about the channel, so I'm quite confused.
Thanks to anyone that can help !

mongolite filtering with dynamic array in r shiny

I have a select input with multiple options and my Mongo query
Here is the array if elements:
c<- c("elen","shallen")
query1 <- paste0('{"client": {"$in"["',c,'"]}')
#sales info is the data base
salesinfo$find(fields = '{"store":true,"_id":false}',query = query1)
Error: Invalid JSON object: {"client": [ elen ]}{"client": [ shallen ]}
this isn't working please help me please remember that it is a dynamic array and the values will change
After extensive research i found a way to solve the issue and i hope my solution will help out guys like me.
q1=paste(shQuote(c, type="cmd"), collapse=", ")
this step is to ensure you print out the array as a string and then use the query
query =paste0('{"store":{"$in":[',q1,']}}')
and the next step would be incorporating it to the query
salesinfo$find(fields = '{"store":true,"_id":false}',query = query)

R writing a function to extract data from an Oracle database

I'm trying to write a function in R, which takes an input and adds it to a pre-defined SQL query. This is to avoid rewriting the same query every time the input changes, and using the function instead.
But I am having problems with the syntax of the function.
The Function
The function takes as input a unique ID, and returns a site name(s).
library(RODBC)
con= odbcConnect(dsn = "DB", uid="morp101", pwd="abcdxyz1234",rows_at_time=500)
getsitename=function(input) {
sitename=sqlQuery(con,"Select DISTINCT(SITE_NAME) FROM SITE_TABLE
WHERE SITE_CODE = '&input&'")
return(sitename)
}
The above function should give the following output when tested
getsitename(1011APQ)
Result: Madison Bay
However the syntax is wrong, not sure how to concatenate the input correctly.
Any advice would be highly appreciated. And apologies for lack of reproducible data, was not sure how I could obtain it for this question.
You can use paste0() to create your query:
getsitename=function(input) {
query = paste0("Select DISTINCT(SITE_NAME) FROM SITE_TABLE WHERE SITE_CODE = '", input, "'")
sitename=sqlQuery(con,query)
return(sitename)
}
So when input='1234', the paste0() statement returns
"Select DISTINCT(SITE_NAME) FROM SITE_TABLE WHERE SITE_CODE = '1234'"

How to create a loop function that will create data frames by using different sql queries

I try to create a loop that will create data frames by using different sql queries that have the same name exept the day number.For example here is the name for query that is for day 1 :SF_2013_Day1_BaseLine and this is for day 6: SF_2013_Day6_BaseLine. I wrote this code (below) but I got an error : Error: unexpected ',' in "for(i in 3," .So any Idea how can i get this code to work ?
Thank you
for (i in 1,3,6,10,14,21,30) {
SF_FinalviewQ3_2013_Day[i]_BaseLine<-sqlQuery(DB,"select * from [SF_2013_Day[i]_BaseLine]");
dim(SF_Day[i]_BaseLine)}
After a change based on #Pgibas edvice to this code :
for (i in c(1,3,6,10,14,21,30)) {
SF_FinalviewQ3_2013_Day[i]_BaseLine<-sqlQuery(DB,"select * from [SF_2013_Day[i]_BaseLine]");
dim(SF_Day[i]_BaseLine)}
I got this error: Error: unexpected input in "for(i in c(3,6)){glm_d[i]_" . What can I do to resolve the problem?
You need to resolve i within the names first:
for (i in c(1,3,6,10,14,21,30)) {
set <- sqlQuery(DB, paste0("select * from [SF_2013_Day[", i, "]_BaseLine]"))
eval(parse(text = paste0("SF_FinalviewQ3_2013_Day", i, "_BaseLine <- set"))
dim(set)
}

db operation exception handling in R

I am using the following function to select values from a table.Table name is given as the parameter to that function.If the table does not exist an error generated and the execution is stoped.I want to do something if the table is not found.Is it possible in R? something like try-catch exception ?
library('RSQLite')
getData <- function(portfolio){
lite <- dbDriver("SQLite", max.con = 25)
db <- dbConnect(lite, dbname = "portfolioInfo.db")
res <- dbSendQuery(db, paste("SELECT * from ",portfolio," ",sep=""))
data <- fetch(res)
return (data)
}
getData("table1")
One way to do this would be to check the class of the data that is returned.
I am not familiar with RSQLite but I guess it will return a dataframe if the table is found and a text error when not?
So a possibility would be to check whether or not an error is raised:
checkQueryResult<-function(data){
if(class(data)=='data.frame') cat('SQL execution worked!')
else cat('Something went wrong, table does not exist?')
}
checkQueryResult(getData("table1"))
But maybe the RSQLite package already has error handling stuff built in?

Resources