如何使用简单的Ruby脚本将数据库表导出为CSV

If you have a Rails project and want to export a table as a CSV, without having to go to all the trouble of finding a gem, installing and using it, then uninstalling it when it’s no longer needed, I have some good news. Here’s an easy and quick way to export a particular table from your database as a CSV file.

如果您有一个Rails项目,并且希望将表导出为CSV,而不必费心查找宝石,安装和使用它,然后在不再需要它时将其卸载,那么我有一些好消息。 这是一种从数据库中将特定表导出为CSV文件的简便快捷的方法。

This is the code that you need to run. You can put it as a rake task and run it, or run it another way.

这是您需要运行的代码 。 您可以将其作为rake任务运行并以其他方式运行。

As you can see, first we import CSV— we need it to do the writing of the CSV file with the data from the database. We then choose the location and the name for the file that we want to export it to, which in our case will be a file called data.csv included under repository public.

如您所见,首先我们导入CSV我们需要它来使用数据库中的数据编写CSV文件。 然后,我们选择要将其导出到的文件的位置和名称,在本例中将是存储库public下包含的名为data.csv的文件。

Then we set the table that we want to export and start writing. We could also change the attributes that we want to export — we don’t have to include them all as they are in the database.

然后,我们设置要导出的表并开始写入。 我们还可以更改要导出的属性-我们不必像在数据库中一样将它们全部包括在内。

That’s it! It’s that simple and yet very helpful.

而已! 就是这么简单,但非常有帮助。

This article was originally published on Medium

本文最初发表于Medium

翻译自: https://www.freecodecamp.org/news/export-a-database-table-to-csv-using-a-simple-ruby-script-2/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值