gpt4 book ai didi

mysql - FasterCSV 教程将数据导入数据库?

转载 作者:太空宇宙 更新时间:2023-11-03 16:09:50 25 4
gpt4 key购买 nike

有人知道任何演示如何使用 FasterCSV 在 Ruby 应用程序中导入数据并将其保存到 SQLite 或 MySQL 数据库的教程吗?

具体步骤如下:

  1. 逐行读取文件(.foreach 方法根据文档执行此操作)
  2. 将文件中的标题名称映射到数据库列名称
  3. 在数据库中为 CSV 数据创建条目(似乎可以在 .foreach block 中使用 .new.save)

这是一个基本的使用场景,但我找不到任何教程,所以任何资源都会有所帮助。

谢谢!

最佳答案

所以看起来 FasterCSV 现在是 Ruby 1.9 的 Ruby 核心的一部分,所以这就是我最终做的,以实现我上面问题中的目标:

@importedfile = Import.find(params[:id])
filename = @importedfile.csv.path
CSV.foreach(filename, {:headers => true}) do |row|
@post = Post.find_or_create_by_email(
:content => row[0],
:name => row[1],
:blog_url => row[2],
:email => row[3]
)
end
flash[:notice] = "New posts were successfully processed."
redirect_to posts_path

find_or_create_by_email 函数内部是从数据库列到 CSV 文件列的映射:row[0]、row[1]、row[2]、row[3 ]

因为它是一个find_or_create 函数,所以我不需要显式调用@post.save 来将条目保存到数据库中。

如果有更好的方法,请更新或添加您自己的答案。

关于mysql - FasterCSV 教程将数据导入数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6238542/

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