开发者

Ruby Class 500 Error

开发者 https://www.devze.com 2023-01-22 13:54 出处:网络
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

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. 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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消