ruby - How so I translate a MySQL statment to a numerical value? -


i fetching data external database, , feeding dashing widget.

when numerical data returned widget, looks like:

mysql::result:0x21a25 

i need data decimal number. here code fetching data , feeding widget:

require 'mysql2'  scheduler.every '1m', :first_in => 0 |job|    # mysql connection    db = mysql2::client.new(:host => "some ip", :username => "user", :password => "password", :port => 3306, :database => "database_name" )    # mysql query    sql = "select count(*) out_sms type = 'standard_sms' "   # execute query   results = db.query(sql)     # update man hours saved e widget    send_event('manhourse', { current: results } )  end 

the mysql2::client#query method return mysql2::result object, ruby enumerable. means can iterate via lots of different means array or hash (results.each {} example), or use enumerable methods .first or .last on it.

your query, having no group by can return 1 row. calling .first give row.

# use alias count, total here sql = "select count(*) total out_sms type = 'standard_sms' " # execute query results = db.query(sql)  # retrieve row using method .first your_row = results.first  # @ hash contains: puts your_row  # value want should hash key puts your_row['total'] 

you can use your_row['total'] in update method.

of course, can simplify , use results.first['total']. don't forget wrap in proper begin ... rescue ... end handle errors.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -