tags:

views:

201

answers:

2

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 the values as shown below.

result = my.query("select * from foo")

result.each do |row| puts row.join(',') end

Thanks for the help!

+1  A: 

 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
klochner
This worked. Thank you.
Poul
A: 

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.

vonconrad