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:
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]}" … |