SQL查询: -
Class Test
def self.execute_mysql(host, database, query)
Net::SSH.start('test.com', user, forward_agent: true) do |ssh|
ssh.exec!("mysql -ppassword -utestuser -h #{host} #{database} -A --execute '#{query}'")
end
end
要运行的命令: -
result = Test.execute_mysql('app', 'sample', 'select * from foo')
结果字符串: -
id name address age
1 ram US 25
2 sam US 30
3 jack India 32
.
.
.
.
100 Peterson US 27
结果变量作为字符串类返回。假设它返回100条记录。我如何遍历每条记录?
答案 0 :(得分:0)
> result
=> "id name address age\n1 ram US 25\n2 sam US 30\n3 jack India 32"
> result.split(" ").each_slice(4){|e| print e }
=> ["id", "name", "address", "age"]["1", "ram", "US", "25"]["2", "sam", "US", "30"]["3", "jack", "India", "32"]
答案 1 :(得分:0)
你的问题的答案取决于很多事情,你需要经过大量的检查才能让它变得健壮。
然而,我会根据一些假设发布一个简单的答案,以帮助您入门。
res = "id name address age
1 ram US 25
2 sam US 30
3 jack India 32"
arr = []
res.each_line {|line| arr << line.split(" ")}
arr
# => [["id", "name", "address", "age"], ["1", "ram", "US", "25"], ["2", "sam", "US", "30"], ["3", "jack", "India", "32"]]
现在,您可以轻松地遍历数组以访问特定属性。