如何使用Ruby DBI的'select_all'与'execute-fetch / each-finish'

问题描述 投票:3回答:2

这是我使用DBI的示例代码:

dbh = DBI.connect("DBI:Mysql:host=#{server};database=mysql", user, pass)
rows = dbh.select_all("SHOW TABLES")

打印的行看起来像:

[["user"], ["user"], ["user"], ["user"], ["user"], ["user"], ["user"], ["user"],
 ["user"], ["user"], ["user"], ["user"], ["user"], ["user"], ["user"], ["user"],
 ["user"]]

这是打印MySQL数据库中的最后一个表,但是记录总数正确。

如果我使用execute-fetch / each-finish序列执行此操作,则类似:

sth = dbh.execute("SHOW TABLES")
sth.each do |row|
  rows << row[0]
end
sth.finish

它给我适当的结果,例如:

["columns_priv", "db", "func", "help_category", "help_keyword", "help_relation",
 "help_topic", "host", "proc", "procs_priv", "tables_priv", "time_zone", "time_z
one_leap_second", "time_zone_name", "time_zone_transition", "time_zone_transitio
n_type", "user"]
ruby dbi
2个回答
2
投票

当我使用DBI.connect("DBI:ODBC:Driver={SQL Server};...")查询MS SQL DB时,也会发生同样的情况>

我的解决方法是将DBI :: Row强制转换为数组:

sth = dbh.execute "..."
begin
  return sth.map{ |row| row.to_a }
ensure
  sth.finish
end

我打赌$ 1,000,这个问题与缓冲区重用有关-一种可能的'性能'增强,具有不良的副作用!


1
投票

我猜想dbh.select_all返回一个Enumerator实例,该实例在每次迭代中产生相同的行。请参阅此伪代码以了解我的意思:

© www.soinside.com 2019 - 2024. All rights reserved.