tags:

views:

138

answers:

4

I'm using R to call a mySQL statement, where I define the variable outside the statement e.g.

foo = 23;
dbGetQuery(con, "select surname from names WHERE age = '.foo.' ;")

But this returns an empty set, I've googled around and tried'.&foo.' ".foo." '".&&foo."' and many different combinations, but none of them work, I think this should be a mysql question rather than an R specific problem I'm having, but not sure. Normally variables have $values but not in R.

A: 

Adding the semi-colon at the end of query sometimes creates problem. Try changing your query from:

dbGetQuery(con, "select surname from names WHERE age = '.foo.' ;")

to:

dbGetQuery(con, "select surname from names WHERE age = '.foo.'")
Sarfraz
Thanks, but it still returns "data frame with 0 columns and 0 rows" where as if I put 23 instead of foo it works fine.
John
what do dot character mean '.foo.'?
Sarfraz
I don't know what the dots mean, I was trying a few different things from other languages I found using different formats.
John
A: 

AFAIK the command has to be a string, so you should append the single components. Not being familiar with R I cant help you out HOW to do that. In MS-VBA the string concatenation operator is '&'.

LuI
+2  A: 

This should work:

foo = 23;

sqlStatement <- paste("select surname from names WHERE age =",foo,'"',sep="")

dbGetQuery(con, sqlStatement;)
Robert
I'd use paste("select surname from names WHERE age =",shQuote(foo),sep="")
Eduardo Leoni
thanks, this also works without the ' ' what are those for Robert? sqlStatement <- paste("select surname from names WHERE age =",foo,sep="")
John
@John. You're correct. The paste function already appends " for you so you don't need '"'. In some instances, when working with strings that have " in them, you can use single ' to wrap the string. This is very useful when dealing with the XML package where strings may have many nested ".
Robert
+2  A: 

You may want to look at the answers to this question: Can I gracefully include formatted SQL strings in an R script?.

The simplest solution is to use the paste command as Robert suggested.

Shane