문제

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
도움이 되었습니까?

해결책

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") }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top