How to use a variable name in a SQL statement? - mysql

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.

This should work:
foo = 23;
sqlStatement <- paste("select surname from names WHERE age =",foo,'"',sep="")
dbGetQuery(con, sqlStatement;)

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.

The accepted answer gives bad advice which leaves your application vulnerable to SQL injection. You should always use bind variables instead of concatenating values directly into your query. Use the dbGetPreparedQUery method as described in this answer: Bind variables in R DBI

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

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 '&'.

Related

Asterisk phrase variables within variables?

I have a odd situation where I would like to phrase a variable inside an SQL string. Basically ODBC will return a query with a string, in that string there will be an Asterisk variable and I need that phrased and passed back to SQL. For example (pointless code but showing the example)-
exten => s,n,Set(QUERY=${ODBC_GET_QUERY(${EXTEN})})
The SQL query in func_odbc.conf is SELECT query FROM tablea WHERE number = ${ARG1}
Now QUERY will look like to = ${DIALED}, ${DIALED} being a asterisk variable (I will make it 17005551212 for example) I need that phrased so I end up with -
exten => s,n,Set(ALLOWED=${ODBC_GET_ALLOWED(${QUERY})})
The SQL query in func_odbc.conf would be SELECT allowed FROM tableb WHERE ${ARG1} so the SQL query would resolve to SELECT allowed WHERE to = 17005551212.
Before I dive into this and re-invent the wheel, is it possible or even allowed? I have actually not tried it yet. I know in a Set() statement it will phrase a variable inline, but is there a way to phrase variable that is in a variable when its returned via ODBC? Thanks!
Please read carefully source code.
Func odbc use prepair call. So it will not work for your example just becuase prepair do not allow do that.
In general you can substitute variables. Example 1 WILL work ok.
Workaround - use mysql EXEC.

Issue using sprintf to insert variable into SQL query

I'm running an R script that grabs a query from MySQL. The query itself is functional, but is dependent on a variable "N".
To add this variable to my SQL code, I'm using sprintf to insert it by typing %s where I'd like it. However, my query also includes multiple of these LIKE statements:
FROM `Receipts`
WHERE `RetailerID`
IN ( '%s' ) # this is where "N" is placed
AND ( `Date` LIKE '%01/07/2014%')
I'm positive that this is the reason my query is not running. The sprintf command is having issue when it reaches these LIKE commands, probably thinking it is similar to %s.
Does anyone know how to get around this so that %01/07/2014% is still printed to the SQL query? I've tried using the escape %% like this, %%01/07/2014%% but it still doesn't work.
Is there a way I can format sprintf so it knows to skip these?
Thanks!
To make #cryo111's comment an explicit answer:
Use gsub like this:
N=10
query="select * from table where table.cnt=#N"
gsub("#N",N,query)
You can use RMySQL's dbEscapeString with sprintf to handle placeholders.
require(RMySQL)
con <- dbConnect(MySQL(), dbname = "foobar")
tmp <- sprintf("SELECT * FROM someField WHERE someOtherField = %s", "sometext")
dbEscapeStrings(con, tmp)
sprintf works fine for me provided I escape the % signs:
x <- "from receipts where retailerid in ('%s') and (date like '%%01/07/2014%%')"
> sprintf(x,"a")
[1] "from receipts where retailerid in ('a') and (date like '%01/07/2014%')"
The above runs just fine for me. However, in general, I wouldn't recommend sprintf over gsub just because it will become cumbersome fairly quickly.
I tend to use paste for sql queries. So in your case I would use something like:
paste("select * from Receipts where RetailerID in(",as.character(N),") and (date like '%01/07/2014%')"

Sql Query LIKE not working

Hi i have trying to do a query, that receives the value on a querystring, but is not working i think the query it self is no good. could you help me?
So i receive the query on
<%String detalhe = request.getParameter("value");%>
I wont put connections and stuff, because they work with other querys, so the problem are not the connections.
// sql query to retrieve values from the specified table.
String QueryString = "SELECT * FROM ebooko.dadoslivros WHERE Autor LIKE '%"+detalhe+"%'
OR ano LIKE '%"+detalhe+"%'";;
rs = statement.executeQuery(QueryString);
It simply cannot retrive the value, i'm querying.
Adicional info:
Table: dadoslivros
Columns that i need to compare the value: Autor, ano.
for example when i run the Href the value that is passed is: Jules%Verne (i gess it changes SPACES with '%'.
Use URLDecoder#decode() to decode the parameters in the query string.
You should also consider using a PreparedStatement to prevent SQL injection attacks.
I solved it changing the query:
String QueryString = "SELECT * FROM dadoslivros WHERE (Data LIKE '%"+detalhe+"%') OR (Autor LIKE '%"+detalhe+"%')";;
maybe it can help another person ;)

problem in where clause of mysql query

Hi
I am generating messahedigest with SHA1 of a file(having extension .eml, as it contains email info)and then storing it to the table named web_de in column messagedigest. Why can't I execute following query in mysql ?? and also not in java...
SELECT slno FROM `webcrawler`.`web_de`
where messagedigest='?Ê'?`®o1F±[øT¤?¿!€' ;
while I could execute query like
SELECT slno FROM `webcrawler`.`web_de`
where messagedigest= ')#Ä€ó…ªã³§°óÚdv~θ`';
Pl note that I am trying to execute that query in mysql workbench 5.2.32 and using mysql 5.1
Can anybody help me out here please ???
Thanks in advance
You have to escape that single quote in the first query:
where messagedigest = '?Ê''?`®o1F±[øT¤?¿!€' ;
Escaping is done by duplicating quotes:
''
(btw: as you see, even the stackoverflow syntax highlighter wasn't able to properly format your string...)
On the other hand, you shouldn't inline values in SQL for various reasons (security, performance). Since you're using Java, use a PreparedStatement instead:
// Prepare a statement with a bind variable : ?
PreparedStatement ps = connection.prepareStatement(
"SELECT slno FROM webcrawler.web_de WHERE messagedigest = ?");
// Bind your string to the first bind variable
ps.setString(1, "?Ê'?`®o1F±[øT¤?¿!€");
// ...
ResultSet rs = ps.executeQuery();
The ' is not being escaped. Replace it with double quotes '' so it reads as:
SELECT slno FROM `webcrawler`.`web_de`
where messagedigest='?Ê''?`®o1F±[øT¤?¿!€';
EDIT: Too slow! :P
You can also escape it by using \' also
the messagedigest value has a quote in it. If you escape the quote it should work, but...
you might be better off encoding the message digest before trying to write it to the database.

I want to Auto add single quotes to my mysql queries

I have couple of mysql queries in perl but some of the values of the where clause contain space between words e.g. the gambia. When my scripts runs with the where clause arguments containing a space it ignore the second word.
I want to know how can I solve this problem i.e. if I type the gambia it should be treated the gambia not the.
If you are using DBI, you can use placeholders to send arbitrary data to database without need to care about escaping. The placeholder is question mark in prepare statement, actual value is given to execute:
use DBI;
$dbh = DBI->connect("DBI:mysql:....",$user,$pass)
or die("Connect error: $DBI::errstr");
my $sth = $dbh->prepare(qq{ SELECT something FROM table WHERE name = ? });
$sth->execute('the gambia');
# fetch data from $sth
$dbh->disconnect();
Edit: If you are composing the query (as you suggested in comments), you can utilize quote method:
my $country = "AND country = " . $dbh->quote('the gambia');
my $sth = $dbh->prepare(qq{ SELECT something FROM table WHERE name = ? $country});
Well, firstly, you should look at using something like DBIx::Class instead of raw SQL in your application.
But if you're stuck with raw SQL, then (assuming that you're, at least, using DBI) you should use bind points in your SQL statements. This will handle all of your quoting problems for you.
$sth = $dbh->prepare('select something from somewhere where country = ?');
$sth->execute('The Gambia');
See the DBI docs for more information about binding.