Ruby Scripting Mysql array 2D for dashing Widgets - mysql

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.

Related

Logging PC data into database via Ruby problem

require 'os'
require 'socket'
require 'mysql2'
require 'etc'
require 'time'
def getBits
return OS.bits.to_s
end
def getPCName
return Socket.gethostname
end
def getUser
return Etc.getlogin
end
info = Hash["SYSBITS " => getBits,"PCN " => getPCName,"USER " => getUser]
for h in info.keys
print h.chomp
end
for b in info.values
print b.chomp
end
connection = Mysql2::Client.new(:host => "localhost", :username => "root",:password => "",:database => "ruby")
result = connection.query("INSERT INTO `mydata`(`#{h}`) VALUES ('#{b}')")
So the idea here is to make Hash of information returned and then use Hash keys as columns and hash values as rows in mysql query but it doesn't work.
I added separation manually because I can't see any other way.
This is the error I'm getting:
_query': Unknown column 'USER ' in 'field list' (Mysql2::Error)

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)

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

Ruby + mysql2 querying fails with variables

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

Turn Ruby Mysql query into variable

I'm currently trying to figure out how to get the username as a ruby variable however I end up getting the following
{"username"=>"test"}
I only want the username text in this case it is test.
client = Mysql2::Client.new(:host => "localhost", :username => "root", :password => "", :database =>"test")
results = client.query("SELECT username FROM accounts").each do |row|
puts row [0]
end
Your code can work with the old mysql/ruby adapter, but not mysql2. By default, mysql2 returns a Hash for each row.
So you can either
puts row['username']
use each(:as => :array) to have the old behaviour.
See GitHub mysql2 project
Maybe you can simplify your code:
results = client.query("SELECT username FROM Accounts").each(:as => :array)
puts results
Here results will be an Array of all the use names.
A full working program:
require 'mysql2'
client = Mysql2::Client.new(:host => "localhost", :username => "", :password => "",
:database =>"test")
results = client.query("SELECT * FROM Movie").each(:as => :array)
results.each { | row | puts row.join("\t") }