Retrieving array from MySQL - 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)

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)

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.

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

How to return MySQL query results from EventMachine?

I'm trying to use EM::Synchrony to speed up my queries by making them async. Following along with the examples from the github page here I'm making 2 asynchronous queries:
EventMachine.synchrony do
db = EventMachine::Synchrony::ConnectionPool.new(size: 2) do
Mysql2::EM::Client.new(
:host => config[:server],
:username => config[:user],
:password => config[:pwd],
:database => config[:db_name]
)
end
multi = EventMachine::Synchrony::Multi.new
multi.add :a, db.aquery("
select count(distinct userid) from my_table
where date = '2013-09-28'
")
multi.add :b, db.aquery("
select count(distinct userid) from my_table
where date = '2013-09-27'
")
res = multi.perform
puts res
# p "Look ma, no callbacks, and parallel MySQL requests!"
# p res.responses[:callback][0]
EventMachine.stop
end
> #<EventMachine::Synchrony::Multi:0x00000001eb8da8>
My question is how do I setup a callback to actually get the values returned by the queries? What I would like to do is once the queries are finished, aggregate them back together and write to another table or csv or whatever. Thanks.
Maybe you don't need Synchrony? They are async anyway. https://github.com/brianmario/mysql2#eventmachine
But if you do need then probably the answer is
res.responses[:callback][:a]
res.responses[:callback][:b]
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/em-multi.rb#L17
What I found is that the following code will give me the results from the queries:
res.responses[:callback].each do
|obj|
obj[1].callback do
|rows|
rows.each do
|row|
puts row.inspect
end
end
end
$ruby async_mysql.rb
{"count(distinct ui)"=>159}
{"count(distinct ui)"=>168}

Ruby hash returning incorrect values

I have the following function in ruby for retrieving certain information from a database.
#Setup
require "mysql2"
#client = Mysql2::Client.new(:host => "127.0.0.1", :username => "root", :password => "password")
query = "use project1"
#client.query(query)
def nodeslastactive
query = "SELECT nodeid FROM nodes WHERE lastactive = #{#clock-1}"
result = #client.query(query)
if result.size == 0
return nil
else
resultarray = Array.new
result.each do |row|
resultarray.push(row["nodeid"])
end
end
end
It is utilized by this code:
lastactivenodes = nodeslastactive
if lastactivenodes != nil
lastactivenodes.each do |lastactivenode|
connect(node,lastactivenode)
end
end
The issue I am getting is that when the connection is established in the 2nd code block, the function tries to connect the node with the value {"nodeid"=>xxxxx}, even though I have copied all hash values out of the hash into an array in the 1st code block for processing by the second block. Any suggestions?
In the first method you miss the
return resultarray
in the else branch, or it will just return the result hash as it is the last thing evaluated in the method