gpt4 book ai didi

mysql - 如何在 Ruby 中将数据库结果保存到文本文件

转载 作者:行者123 更新时间:2023-11-29 08:50:49 25 4
gpt4 key购买 nike

我正在尝试将查询结果存入数据库并将其保存到 csv 文件中。这是我当前的 Ruby 脚本。

#! /usr/bin/ruby

require 'rubygems'
require 'mysql'
require 'date'

# need mysql queries here / use mysql2 calls
db_con = Mysql.new("localhost", "root", "", "msd")

date_results = db_con.query("SELECT CONCAT(CONVERT(date_format(dd.date, '%b-%e'),char),'\\n') AS date
FROM msd.date_dim dd LEFT OUTER JOIN msd.results cs
ON dd.id = cs.date_id
GROUP BY
dd.date")

# create new xml file and insert header
open('test_trend.xml', 'w') do |f|
date_results.each_hash do |f|
f.puts "#{f['date']}"
end
end

我收到以下错误。第 23 行是 date_results.each_hash 行。

so_test.rb:24:in `block (2 levels) in <main>': private method `puts' called for {"date"=>"Jun-12\n"}:Hash (NoMethodError)
from /Users/pierce/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/ruby-mysql-2.9.9/lib/mysql.rb:686:in `call'
from /Users/pierce/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/ruby-mysql-2.9.9/lib/mysql.rb:686:in `each_hash'
from so_test.rb:23:in `block in <main>'
from so_test.rb:22:in `open'
from so_test.rb:22:in `<main>'

如有任何建议,我们将不胜感激。谢谢。

最佳答案

在嵌套 block 中,您将覆盖 f 变量。相反,尝试类似的方法:

# create new xml file and insert header
open('test_trend.xml', 'w') do |f|
date_results.each_hash do |hash|
f.puts "#{hash['date']}"
end
end

关于mysql - 如何在 Ruby 中将数据库结果保存到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11280445/

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