MacLochlainns Weblog

Michael McLaughlin's Technical Blog

Site Admin

Ruby-MySQL Columns

with one comment

Last week I posted how to configure and test Ruby and MySQL. Somebody asked me how to handle a dynamic list of columns. So, here’s a quick little program to show you how to read the dynamic list of column (and this updated blog post has the 2024 update for the new Mysql2 ODBC driver):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
require 'rubygems'
require 'mysql'
 
# Begin block.
begin
  # Create a new connection resource.
  db = Mysql.new('localhost','student','student','studentdb')
 
  # Create a result set.
  rs = db.query('SELECT item_title, item_rating FROM item')
  # Read through the result set hash.
  rs.each do | row |
    out = ""
    i = 0
    while i < db.field_count
      # Check if not last column.
      if i < db.field_count - 1
        out += "#{row[i]}, "
      else
        out += "#{row[i]}"
      end
      i += 1
    end
    puts "#{out}"
  end
  # Release the result set resources.
  rs.free
rescue Mysql::Error => e
  # Print the error.
  puts "ERROR #{e.errno} (#{e.sqlstate}): #{e.error}"
  puts "Can't connect to MySQL database specified."
  # Signal an error.
  exit 1
ensure
  # Close the connection when it is open.
  db.close if db
end

The new logic on lines 13 through 22 reads the list of columns into a comma delimited list of values. The if-block checks to make sure it doesn’t append a comma to the last column in the list. It prints output like:

The Hunt for Red October, PG
Star Wars I, PG
Star Wars II, PG
Star Wars II, PG
Star Wars III, PG13
The Chronicles of Narnia, PG
RoboCop, Mature
Pirates of the Caribbean, Teen
The Chronicles of Narnia, Everyone
MarioKart, Everyone
Splinter Cell, Teen
Need for Speed, Everyone
The DaVinci Code, Teen
Cars, Everyone
Beau Geste, PG
I Remember Mama, NR
Tora! Tora! Tora!, G
A Man for All Seasons, G
Hook, PG
Around the World in 80 Days, G
Harry Potter and the Sorcerer's Stone, PG
Camelot, G

As always, I hope this helps those looking for a solution.

Written by maclochlainn

April 18th, 2015 at 2:25 am