I'm using the Ruby mysql module.
I want to print out the results of a query and include the column names. I'm having trouble finding the method to give me an array of these names. I have t开发者_C百科he values as shown below.
result = my.query("select * from foo")
result.each do |row| puts row.join(',') end
Thanks for the help!
result.fetch_fields.each_with_index do |info, i|
printf "--- Column %d (%s) ---\n", i, info.name
printf "table: %s\n", info.table
printf "def: %s\n", info.def
printf "type: %s\n", info.type
printf "length: %s\n", info.length
printf "max_length: %s\n", info.max_length
printf "flags: %s\n", info.flags
printf "decimals: %s\n", info.decimals
end
This may not directly answer your question, but you might benefit from checking out a database abstraction layer. There are several of them for Ruby, most notably ActiveRecord. ActiveRecord comes bundled as the model part of the Ruby on Rails framework, but you can use it "stand-alone" without the rest of Rails.
With it (or something similar) you will be able to more rapidly and accurately create applications, as it provides invaluable tools to communicating with your database--tools you would spend a lot of time developing yourself. Should you ever choose to change your database vendor from MySQL to something else (PostgreSQL or Oracle, for example), you won't have to recode much.
The method you are searching for is Mysql2::Result#fields
. In example:
> result = ActiveRecord::Base.connection.execute('SELECT 1 as "first_column_name", 2 as "second_column_name"')
=> #<Mysql2::Result:0x0000559c8b9d8370...
> result.fields
=> ["first_column_name", "second_column_name"]
精彩评论