Ruby Class 500 Error
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
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 toreturn
from here since it is not possible to query a nil object.- You probably need
require 'rubygems'
at the start, beforerequire 'mysql'
(if running as an independent file) if row['id'].nil
should beif row['id'].nil?
Instead of coding your own MySQL adapter, try ActiveRecord, DataMapper on any other ORM to make your life easier.
精彩评论