在Windows下,如果使用了mysql 5.1, 安装时可能正确,但是执行查询时,使用each_hash方法时就会报错,
mysql in `each_hash': NULL pointer given (ArgumentError)。这时可能是因为mysql5.1里带的libmySQL.dll与ruby不兼容所致,下子一个老版本的,放到ruby的bin下即可。下载地址
http://instantrails.rubyforge.org/svn/trunk/InstantRails-win/InstantRails/mysql/bin/libmySQL.dll
程序见下面。
require "rubygems"
require "mysql"
begin
dbh = Mysql.real_connect("localhost", "root", "123456", "iread")
res = dbh.query("SELECT * FROM t_ir_channel")
# res.each do |row|
# printf "%s, %s /n", row[0], row[1]
# end
res.each_hash do |f|print "#{f['id']} -- #{f['name']} "end
puts "Server version: " + dbh.get_server_info
rescue Mysql::Error => e
puts "Error code: #{e.errno}"
puts "Error message: #{e.error}"
puts "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?("sqlstate")
ensure
dbh.close if dbh
end