How to use LIKE command inside SQL query of R - r

I'm new to R, I'm trying to use 'like' command inside R query but its throwing error...i'm attaching the code , please be kind enough to rectify the same...
let from i am passing med= ABC from API end..
med_aff1<- function(med,sex)
{
affModel <- dbGetQuery(jdbcConnection ,
"SELECT * from XYZ WHERE MEDICINE %LIKE% %'",med,"'% AND SEX ='",M,"')
return(affModel)
}

Related

Query is unable to match parts after "/" or parts within "()" in the data

I have a search request written as
import sqlite3
conn = sqlite3.connect('locker_data.db')
c = conn.cursor()
def search1(teacher):
test = 'SELECT Name FROM locker_data WHERE Name or Email LIKE "%{0}%"'.format(teacher)
data1 = c.execute(test)
return data1
def display1(data1):
Display1 = []
for Name in data1:
temp1 = str(Name[0])
Display1.append("Name: {0}".format(temp1))
return Display1
def locker_searcher(teacher):
data = display1(search1(teacher))
return data
This allows me to search for the row containing "Mr FishyPower (Mr Swag)" or "Mr FishyPower / Mr Swag" with a search input of "FishyPower". However, when I try searching with an input of "Swag", I am then unable to find the same row.
In the search below, it should have given me the same search results.
The database is just a simple 1x1 sqlite3 database containing 'FishyPower / Mr Swag'
Search Error on 'Swag'
Edit: I technically did solve it by limiting the columns being searched to only 'Name' but I intended the code search both the 'Name' and 'Email' columns and output the results as long as the search in within either or both columns.
Edit2: SELECT Name FROM locker_data WHERE Email LIKE "%{0}%" or Name LIKE "%{0}%" was the right way to go.
I'm gonna guess that Mr. FishyPower's email address is something like mrFishyPower#something.com. The query is only comparing Email to teacher. If it was
WHERE Name LIKE "%{0}%"
OR Email LIKE "%{0}%"'
you would (probably) get the result you want.

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'"

unable to run sql query against oracle table in 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.

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