Question

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
Was it helpful?

Solution

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

  1. puts row['username']
  2. 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") }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top