1

I am writing an application in R that makes parameterized queries and sends them to a database to return the applicable information to a data table in the application. Because of the nature of a search query, I need to use the SQL term LIKE, with % signs around the search term. And to protect the database from SQL injection, I need to use the sqlInterpolate function. But I'm having issues with the way the sqlInterpolate function is making the query.

Right now, when I go into the R console, this works:

> sql <- sqlInterpolate(conn, "SELECT * FROM table WHERE Column1 LIKE '%000g7%'")
> dbGetQuery(conn, sql)

But this doesn't,

> str <- "000g7"
> sql <- sqlInterpolate(conn, "SELECT * FROM table WHERE Column1 LIKE '%?search%'", search = str)
> dbGetQuery(conn, sql)

it just returns an empty list. If I could get some help with the syntax of the query, I'd greatly appreciate it. I'm almost positive it has something to do with the apostrophes or something along those lines. Or if there is a better way to do this, I'm all ears.

1
  • What you wrote is definitely the way you would do this in most other programming languages. I can't test locally because I don't even know which package the OP is using. Commented Oct 7, 2019 at 15:04

1 Answer 1

4

In the case of the LIKE operator, the % are really part of the string you are searching with, so you just need to add those to the value you are searching for before you interpolate the value into the query. You should use

str <- "000g7"
sql <- sqlInterpolate(conn, "SELECT * FROM table WHERE Column1 LIKE ?search", 
  search = paste0("%", str, "%"))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.