Using a variable in Ruby Mysql query - mysql

I have a name stored in the variable username and would like to pull users row information when I try
result = dbh.query("SELECT * FROM maintab WHERE user = '#{username}'")
I get no results. If I put in the username by hand however, it does return a result. How format my query so that I may use variables?

Try to debug this way:
username = "Peter" # any of your real name
result = dbh.query("SELECT * FROM maintab WHERE user = '#{username}'")
it should work. Looks like your username is nil or blank

Open up IRB and try to print what you have.
How does #{} behave with single quotes vs escaped double quotes?
That should answer your question.

Related

Why I am not getting result of this query ,in rails?

I am trying to get rows from mysql in rails by following query.I am trying first it on console.But this is not working,please help me.
name="vikash"
List=User.find_by_sql["SELECT * from users where name like ?",%#{name}%]
A small mistake in your query.
Space after find_by_sql and name interpolation should be done with double quote.
name = "vikash"
list = User.find_by_sql ["SELECT * from users where name like ?", "%#{name}%"]
Check below links for details
http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_like
http://apidock.com/rails/ActiveRecord/Querying/find_by_sql
Hope this will help you...
Do not put variable directly into the conditions string will pass the variable to the database as-is. This means that it will be an unescaped variable directly from a user who may have malicious intent.
You can check in console by name = "vikash'" and query with the query shown by #sanju
User.find_by_sql("SELECT * from users where name like '%#{name}%'")
And see the difference how malicious characters are escaped by querying with
list = User.find_by_sql ["SELECT * from users where name like ?", "%#{name}%"]
For further information visit:
http://guides.rubyonrails.org/active_record_querying.html
https://railsguide.wordpress.com/2016/03/02/sanitizing-user-input-while-quering/
Try updating your find_by_sql to the following:
User.find_by_sql(["SELECT * from users where name like ?", "%#{name}%"])
use this code:
list= User.find_by_sql("SELECT * from users where name like '%#{name}%'")
Try this query
User.find_by_sql("SELECT * from users where name like '%#{name}%'")

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 ;)

The data reader has more than one field. Multiple fields are not valid for EDM primitive types

I am trying to delete multiple rows from the table using linq's ExecuteStoreQuery method like this
string query = "delete from IMPORTStatistics where districtid='" + districtId + "'";
db.ExecuteStoreQuery<int>(query);
but it is throwing this exception
"The data reader has more than one field. Multiple fields are not valid for EDM primitive types."
What am I doing wrong?
Just for the information, I am using MySql.
Given that you're executing a delete command (not a query), I think you should be using ExecuteStoreCommand instead of ExecuteStoreQuery.
Additionally, you should definitely be using parameters instead of putting the ID directly into the command.
string command = "delete from IMPORTStatistics where districtid={0}";
int rowsDeleted = db.ExecuteStoreCommand(command, districtId);
This is really helpful link after goggling I found this
http://welcometoaspdotnet.blogspot.com/2012/08/execute-stored-procedure-with-entity.html
thx

odd sql error, variable not being recognized correctly

I'm currently in hour two of this issue, I can't explain it so I will simply show what is going on. I don't know if this matters at all, but I am using the linkedIN API to retrieve a user's linkedIn unique ID.
In English, what I'm doing:
User Signs in with LinkedIn
I read-in user's LinkedIn ID (returned from the API)
If ID exists in database, say "hello", if not, show them a form to register
The issue I am having:
The following line works and properly returns the 1 user I have in the database with a linkedIn ID of OtOgMaJ2NM
$company_data = "SELECT * FROM s_user WHERE `LI_id` = 'OtOgMaJ2NM'";
The following query returns no results - using the same database with the same record in the table s_user:
$linkedIn_id = "<?js= id ?>";
echo $linkedIn_id;
The following code outputs OtOgMaJ2NM with no trailing spaces.
So far so good ... expcept when I run the query this time using the variable, no records are returned!
$company_data = "SELECT * FROM s_user WHERE `LI_id` = '$linkedIn_id'";
Further notes:
When I echo $company_data the same query is displayed when I use the variable as did when I used the plain text version of the query.
Anyone have ANY ideas?
Thanks,
Evan
I can only assume that when echoing variables it strips the tags, so when you're using it with the query you're actually saying:
$company_data = "SELECT * FROM s_user WHERE `LI_id` = '<?js= OtOgMaJ2NM ?>'";
I could be wrong, but have you tried stripping the tags from the variable?
If you send the variable between the "", the MySQL engine will search for $linkedIn_id literally and not for its content.
Seems you are using php, but I'm not sure about the right syntax. Take a look in the docs.

How to use a variable name in a SQL statement?

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