为什么这不正确。怎么了???
#!/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
答案 0 :(得分:1)
ensure
。因此,您尝试查询已关闭的连接。所以从ensure中删除con.close。您可能希望从此处return
,因为无法查询nil对象。require 'rubygems'
开始之前需要require 'mysql'
(如果作为独立文件运行)if row['id'].nil
应为if row['id'].nil?
答案 1 :(得分:0)
不要编写自己的MySQL适配器,而是在任何其他ORM上尝试ActiveRecord,DataMapper,以使您的生活更轻松。