Ruby + DBI + MySQL:未定义的方法`to_ary' for nil:NilClass(NoMethodError)

时间:2014-03-26 10:18:23

标签: mysql ruby dbi

我正在尝试连接MySQL起诉DBI。我正在关注Using the Ruby DBI Module文档。

这是我的代码:

require 'dbi'
begin
  dbh = DBI.connect("DBI:Mysql:<db_name>:<mysql_hostname>", "<mysql_user>", "<mysql_password>")
  row = dbh.select_one("SELECT VERSION()")
  puts "Server version: " + row[0]
rescue DBI::DatabaseError => e
  puts "Something went wrong connecting the database"
  puts e.errstr
end

sth = dbh.prepare("SHOW TABLES")
sth.execute

while row = sth.fetch
  puts row
end

sth.finish
dbh.disconnect

此代码失败,错误如下:

Server version: 5.6.13-log
/home/user/dbi_testing.rb:14:in `puts': undefined method `to_ary' for nil:NilClass (NoMethodError)

在上面的错误中,我打印MySQL版本(服务器版本:5.6.13-log)只是为了确保我与数据库有良好的工作连接。

上面的while循环抛出此错误。所以我把它改成了以下:

sth.fetch do |row|
  puts row
end

仍然得到完全相同的错误。

因此,这意味着 sth.fetch 方法不存在或者我访问它的方式有问题。

你能帮我解决这个错误。

更新:我取得了一些进展,如果我按照下面的说法,我可以看到表格:

sth.fetch_hash do |row|
  puts row
end

输出结果为:

Server version: 5.6.13-log
{"Tables_in_mstrmd"=>"DSSCSADDRESS"}
{"Tables_in_mstrmd"=>"DSSCSBADGETB"}
{"Tables_in_mstrmd"=>"DSSCSCONTACT"}
{"Tables_in_mstrmd"=>"DSSCSDEVCKEY"}
{"Tables_in_mstrmd"=>"DSSCSPSNLZTN"}
{"Tables_in_mstrmd"=>"DSSCSRCOLCON"}
{"Tables_in_mstrmd"=>"DSSCSRINSTRG"}
{"Tables_in_mstrmd"=>"DSSCSSUBINST"}
{"Tables_in_mstrmd"=>"DSSCSSYSPROP"}
{"Tables_in_mstrmd"=>"DSSMDJRNINFO"}
{"Tables_in_mstrmd"=>"DSSMDJRNLNKS"}
{"Tables_in_mstrmd"=>"DSSMDJRNOBJC"}
{"Tables_in_mstrmd"=>"DSSMDJRNOBJD"}
{"Tables_in_mstrmd"=>"DSSMDJRNOBJS"}
{"Tables_in_mstrmd"=>"DSSMDLNKITEM"}
{"Tables_in_mstrmd"=>"DSSMDLNKPROP"}
{"Tables_in_mstrmd"=>"DSSMDOBJBLOB"}
{"Tables_in_mstrmd"=>"DSSMDOBJCMNT"}
{"Tables_in_mstrmd"=>"DSSMDOBJDEF2"}
{"Tables_in_mstrmd"=>"DSSMDOBJDEFN"}
{"Tables_in_mstrmd"=>"DSSMDOBJDEPN"}
{"Tables_in_mstrmd"=>"DSSMDOBJINFO"}
{"Tables_in_mstrmd"=>"DSSMDOBJLOCK"}
{"Tables_in_mstrmd"=>"DSSMDOBJPROP"}
{"Tables_in_mstrmd"=>"DSSMDOBJSECU"}
{"Tables_in_mstrmd"=>"DSSMDOBJTRNS"}
{"Tables_in_mstrmd"=>"DSSMDSYSPROP"}
{"Tables_in_mstrmd"=>"DSSMDUSRACCT"}

因此,当我使用 sth.fetch_hash 时,我可以看到这些表格。那么 sth.fetch 有什么问题?

任何指针都会有很大的帮助。

更新(替代方法):

我跑了puts sth.methods.sort,这是输出:

fetch
fetch_all
fetch_array
fetch_hash
fetch_many
fetch_scroll
fetchable?

我将 sth.fetch 更改为 sth.fetch_array ,现在我可以看到表格很好。

信用额度由comment

转到此@philant

所以,在某种程度上,我的问题有一个解决方法。

但我仍然想知道为什么方法 sth.fetch 不起作用?任何解释都会非常有用。

0 个答案:

没有答案