csv - Grails:将已解析的CSV数据保存到数据库

标签 csv parsing grails

我已经使用grails插件成功地通过csv进行了解析。现在输出如下:

这就是我解析csvFile的方式。我需要将此csv内容保存到数据库中。我该怎么做?

def upload = {
    def f = request.getFile('filecsv')
    if (f.empty) {
        flash.message = 'file cannot be empty'
        render(view: 'uploadForm')
        return
    } else {

        def file = request.getFile('filecsv')
        def singlerow = file.inputStream.toCsvReader(['charset': 'UTF-8', 'separatorChar': '|']).eachLine{
            line ->
                println "The data are"+line


        }
    }
}

输出看起来像
The data are[test, 2017-08-21, , , 2017-08-21, 100, 8668a73e55e0824c130337d49f0fc746, , Annual, , , , , , , , , , , , , , , , , , , , , test, 1111, test, test, 1901-03-13, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , asd/asd/sad/incentive/20170906/09062017.csv, 2017-09-06, , 4.7, 30430001]
The data are[test, 2017-10-07, , , 2017-08-07, 100, asdasdasdasd, , An, , , , , , , , , , , , , , , , , , , , , test, 1111, test, test, 1900-02-15, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , stat/test/test/incentive/20170906/ 09072017.csv, 2017-09-06, , 4.7, 30430001]

我的网域类别:
class Data {

String data1
Date data12
Date data13
Date data14
Date data15
String data16
String data17
String data18
String data19
String data110
String data111
String data112
String data113
String data114
String data115
String data115
String data116
String data117
String data118
String data119
String data120
_____________
__________
___________

}
我如何将其保存到该域类的数据库。

最佳答案

在不知道其他细节的情况下,我想到的最简单的保存此类域实例的方法是:

static dates = [ 11, 12, 13, 14 ] // positions of fields to be converted to Date

def upload = {
  //...
  file.inputStream.toCsvReader(['charset': 'UTF-8', 'separatorChar': '|']).eachLine{ line ->
    def map = [:]
    line.eachWithWithIndex{ d, ix -> 
      // if( d ) map[ "data${ix+1}" ] = dates.contains( ix ) ? Date.parse( 'yyyy-MM-dd', d ) : d
      if( d ) map[ "data${ix+1}" ] = d // if you need no date conversion
    }
    Data data = new Data( map )
    if( !data.save() ) log.warn "save failed: $data.errors"
  }
}

关于csv - Grails:将已解析的CSV数据保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50488398/

相关文章:

python - 如何验证pandas.read_csv读取的csv数据?

php - 我应该在 PHP 中使用什么 RSS 解析器?

java - 用hadoop获得csv文件最大值(value)的更好方法是什么?

python-3.x - 显示多个满足特定条件的数据-PANDAS 中的问题

python - 从 GCS 获取大量 csv 文件到 BQ

xml - 如何解析 Google Refine 中的 XML 以提取数据?

java - java中读取和写入数据到文件中,数据中带有双引号

ruby-on-rails - Ruby on Rails 或 Grails 的开发人员生产力更高吗?

css - 使用 Grails 资源插件 1.2.7 破坏的 CSS 文件中的 URL

pdf - Grails 渲染 PDF 文件