tags:

views:

26

answers:

2

Why is this not correct. What is wrong with it??

#!/usr/bin/ruby

require "mysql"

class Game
  attr_accessor :id, :name, :urlName, :description, :hits, :categorys, :width, :height, :nilGame

  def load(id)
    #Load mysql
    begin
        # connect to the MySQL server
        con = Mysql.new('localhost', 'user', 'pass', 'database')
    rescue Mysql::Error => e
        puts "mysql error"
        ensure
        # disconnect from server
        con.close if con
    end
    rs = con.query("select * from games where id='#{id}' limit 1")
    rs.each_hash do |row|
      if row['id'].nil
        @nilGame = true
      else
            @id = id
            @name = row['name']
            @urlName = row['urlname']
            @description = row['description']
            @hits = row['hits']
            @categorys = row['categorys']
            @width = row['width']
            @height = row['height']
      end
    end
    con.close
  end
end
+1  A: 
  1. ensure is always called, no matter if an exception was raised or not. So you trying to query on a closed connection. So remove the con.close from ensure. You might want to return from here since it is not possible to query a nil object.
  2. You probably need require 'rubygems' at the start, before require 'mysql' (if running as an independent file)
  3. if row['id'].nil should be if row['id'].nil?
Swanand
Thanks this stopped the error but it still returns nil for every column??
Will03uk
Try `puts row.inspect` as the first statement in the loop. You will get a better idea of what is returned. It might be that the columns are actually empty.
Swanand
I created 3 instances of the class called id 1, 2 and 3 and it only puts row.inspect once and then it stopped. So it's not finishing the page??
Will03uk
That is because of `limit 1`.
Swanand
A: 

Instead of coding your own MySQL adapter, try ActiveRecord, DataMapper on any other ORM to make your life easier.

Ariejan