0

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

1 Answer 1

1

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") }
Sign up to request clarification or add additional context in comments.

2 Comments

Hey @prnoo thank you for your response I'm currently getting syntax errors with your second option any ideas?
Just added a working test. I am using ruby 2.0.0p353 (2013-11-22) [x86_64-linux]. Good luck :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.