Logging PC data into database via Ruby problem - mysql

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)

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.

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 can I update specific row in db with csv file?(rails)

I've used csv files for initial data to MySQL database. The method below was for that import process.(I asked it before in here stackoverflow, so it might be the case that I don't understand fully this process until now..)
# lib/tasks/import.rake
require 'csv'
namespace :db do
task :restaurants => :environment do
CSV.foreach('public/seed_data/restaurants.csv') do |row|
record = Restaurant.new(
:name => row[0],
:addr => row[1]
)
record.save!
end
end
end
But now I have to just update some specific rows which has changed after my first db import. So I just changed my first method like below. My update.csv file has id, name(updated), addr(updated) columns with no head.
# lib/tasks/import.rake
require 'csv'
namespace :db do
task :restaurants_update => :environment do
CSV.foreach('public/seed_data/update.csv') do |row|
n = row[0]
record = Restaurant.find(n)
record.update_attributes(
:name => row[1],
:addr => row[2]
)
record.save!
end
end
end
I thought it can read specific rows with row[0] which has restaurant_id to update, then update name and address with the followings(row[1] and row[2]). However when I do rake db:restaurants_update, it's saying ActiveRecord::RecordNotFound: Couldn't find Restaurant with id=1000001(it is my first row in csv file and my database has this record with id 1000001. I checked it out in console Restaurant.find(1000001)). I think import.rake might be missing my records.(can't read existing databases?)
Can anyone point out my faults?
If you are only updating, use find_by(id: n). Personally, I'd recommend find_or_create_by, which would either update the field or create a new one if it's not present.
# lib/tasks/import.rake
require 'csv'
namespace :db do
task :restaurants_update => :environment do
CSV.foreach('public/seed_data/update.csv') do |row|
n = row[0]
record = Restaurant.find_or_create_by(id: n)
record.update_attributes(
:name => row[1],
:addr => row[2]
)
record.save!
end
end
end

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