gpt4 book ai didi

mysql - 如何遍历 MySQL 结果集?

转载 作者:IT老高 更新时间:2023-10-29 00:13:14 28 4
gpt4 key购买 nike

这是我正在使用的代码:

# Run the query against the database defined in .yml file.
# This is a Mysql::result object - http://www.tmtm.org/en/mysql/ruby/
@results = ActiveRecord::Base.connection.execute(@sql_query)

在我看来,这是我为查看值所做的工作:

<pre><%= debug @results %></pre>
Outputs: #<Mysql2::Result:0x007f31849a1fc0>

<% @results.each do |val| %>
<%= val %>
<% end %>
Outputs: ["asdfasdf", 23, "qwefqwef"] ["sdfgdsf", 23, "asdfasdfasdf"]

假设我查询了类似select * from Person 的查询,它返回的结果集如下:

ID      Name      Age
1 Sergio 22
2 Lazlow 28
3 Zeus 47

如何遍历每个值并输出它?

这里的文档没有用,因为我已经尝试过应该存在的方法,但是解释器给我一个错误,说这些方法不存在。我使用了错误的文档吗?

http://www.tmtm.org/en/mysql/ruby/

谢谢!

最佳答案

如果您使用的是 mysql2 gem,那么您应该获得 mysql2 结果对象,并且根据文档,您应该能够执行以下操作

results.each do |row|
# conveniently, row is a hash
# the keys are the fields, as you'd expect
# the values are pre-built ruby primitives mapped from their corresponding field types in MySQL
# Here's an otter: http://farm1.static.flickr.com/130/398077070_b8795d0ef3_b.jpg
end

查看文档 here

所以在您的情况下,您可以执行以下操作

<% @results.each do |val| %>
<%= "#{val['id']}, #{val['name']}, #{val['age']}" %>
<% end %>

编辑:您似乎指的是错误的文档,请查看 Mysql2 gems 文档。

关于mysql - 如何遍历 MySQL 结果集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10836805/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com