Ruby + mysql2 querying fails with variables - mysql

Working with Ruby 2.0, Qt4 gem and Mysql2 gem. I need to compare the text of two lineedit and make a query with them, which is a failure so far.
client = Mysql2::Client.new(:host => "localhost", :username => "root", :password => "123456", :database => "school")
# text of both lineedits saved into local variables
tName=#leName.text()
tPass=#lePass.text()
#then
res= client.query("SELECT usr_name, usr_pass, usr_tipo FROM user WHERE usr_name = tName AND usr_pass = tPass")
The only thing that fails is that query. I've tried to put the local variable as global (#tName, #tPass), or put them into #{}, which search for columns in the table user named tName and tPass, also tried to put them into '' but that only search for a user named tName.
I want the query to search for usr_name= "text inside tName". What am I doing wrong?
EDIT: if you are wondering, tName, tPass are strings and the fields usr_name and usr_pass are varchar(50).

Looks like you didn't interpolate the variables. do the following
res= client.query("SELECT usr_name, usr_pass, usr_tipo
FROM user
WHERE usr_name = '#{tName}' AND usr_pass = '#{tPass}'")

Related

Retrieving array from MySQL

I'm not using sqlite3 gem
I'm using mysql2 gem
I'm retrieving data from MySQL database given that it meets the condition of a certain event type and severity. However, it returns only one row instead of an array of results. It really puzzles me. Shouldnt .map return an array?
result = connect.query("SELECT * FROM data WHERE event_type = 'ALARM_OPENED' AND severity = '2'")
equipments = result.map do |record|
[
record['sourcetime'].strftime('%H:%M:%S'),
record['equipment_id'],
record['description']
]
end
p equipments
I had misread your question...I think what you are looking for is in here.
UPDATE
You can use each instead, like this:
#!/usr/bin/env ruby
require 'mysql2'
connect= Mysql2::Client.new(:host => '', :username => '', :password => '', :database => '')
equipments = []
result = connect.query("SELECT * FROM data WHERE event_type = 'ALARM_OPENED' AND severity = '2'", :symbolize_keys => true).each do |row|
equipments << [
row[:sourcetime].strftime('%H:%M:%S'),
row[:equipment_id],
row[:description]
]
end
puts "#equipments {equipments}"
EDITED:
I forgot to add .each at the end of the query. So it was returning the initialized empty array instead.
You must need to change your sql statement :
result = connect.query("SELECT * FROM data WHERE event_type = 'ALARM_OPENED' AND severity = '2'", :as => :array)

Ruby Scripting Mysql array 2D for dashing Widgets

I've been struggling with this for almost two weeks now and I hope someone may help me out on how to convert my sql query from mysql db into 2D array for sending into the google charts widgets in dashing please?
My actual .rb script (Job) does this >
require 'mysql2'
SCHEDULER.every '1m', :first_in => 0 do |job|
points = []
# Mysql connection
db = Mysql2::Client.new(:host => "192.168.xx.xx", :username => "xxxx", :password => "xxxxxx", :port => 3306, :database => "xxxxxx" )
# Mysql query
sql = "SELECT * FROM Table"
###Field 1 is Integer
###Field 2 is Decimal(65,30)
rs = db.query(sql, :as => :array)
subpoints = []
subpoints.push('Week')
subpoints.push('MTV')
points.push(subpoints)
rs.each do |row|
subpoints = []
subpoints.push(row['Field 1'])
subpoints.push(row['Field 2'])
points.push(subpoints)
end
###Update the List widget
send_event('mychart01', points: points)
Mysql2.close
end
I get the error:
./mysql_chart_01.rb:23:in []': no implicit conversion of String into Integer (TypeError) from ./mysql_chart_01.rb:23:inblock in '
from ./mysql_chart_01.rb:21:in each' from ./mysql_chart_01.rb:21:in'
Actually I'm not even sure to be able to make it work this way. Does anyone has a better suggestion or a Ruby script for Google charts?
Best regards.

Ruby Mysql2 Client not taking backslash while insert

We are using production and staging databases in our application.
Our requirement is to insert all the records to staging database when ever a record is added in production database, so that both the servers are consistent and same data.
I have used Mysql2 client pool to connect to staging server and insert the record that is added to production.
here is my code:
def create
#aperson = Person.new
#person = #aperson.save
if #person && Rails.env == "production"
#add_new_person_to_staging
client = Mysql2::Client.new(:host => dbconfig[:host], :username => dbconfig[:username], :password => dbconfig[:password], :database => dbconfig[:database])
#person_result = client.query('INSERT INTO user_types(user_name, regex, code) Values ("myname" , "\.myregex\." , "ns" );')
end
end
Here "#person_result" record is inserted to mysql table but the "regex" column eliminates "\" slashes.
like : user_name = myname, regex = .myregex., code = ns
when I manually execute the "Insert" query in mysql command line it inserts as it is along with \ slash. but not through "client.query"
Why does \ slash is eliminated. please help me here.
Thanks.
\ is likely being removed by the MySQL2 client as part of a SQL injection protection preprocessor.
Have you looked at trying either a double backslash or using the escape method to properly escape the string?
Try using this
#person_result = client.query('INSERT INTO user_types(user_name, regex, code) Values (myname , "\."+myregx+".\" , ns )')

SQL Error with ruby

require 'mysql2'
SCHEDULER.every '2h', :first_in => 0 do |job|
# MySQL connection
db = Mysql2::Client.new(:host => "host", :username => "username", :password => "password", :port => port, :database => "database" )
sql = "select count(*) from tickets where department_id = 6;"
tickets_sql = db.query(sql)
puts tickets_sql
#Send Events
send_event('tickets_sql', {current: tickets_sql})
end
I am using the puts command so I can see the output in my log file. The output of this command is an error message which is: #<Mysql2::Result:0x000000025546a8>
What does this error mean?
I took the same exact query as in the code and ran it on the database and it outputs the number as expected.
It is not an error message, it is an object (Mysql2::Result). You can give count(*) and alias (put as smth after it) and access as tickets_sql.first['smth'] (you can use first as there is only one row, otherwise you get a collection, so you should iterate through it with .each, for example, to output retrieved rows with puts).

Get last inserted id using mysql2 gem

I have code like this:
require 'mysql2'
#db.query("insert into clients (Name) values ('#{client}')")
Can I return last inserted id with 1 query?
You can use last_id method of the client instance:
client = Mysql2::Client.new(:host => "localhost", :username => "root", :password => "", :database => "db")
insert = client.query "INSERT INTO test (name, date) VALUES ('name', '2011-11-28 09:13:56')"
id = client.last_id
http://rubydoc.info/gems/mysql2/0.2.6/Mysql2/Client:last_id
Edit: it doesn't answer your original question but still looks better than call for LAST_INSERT_ID
I don't anything about gem but you can try to run
#db.query("SELECT LAST_INSERT_ID();")
after your first query.