Grails中解析CSV并导出到Mysql数据库

2021-12-22 00:00:00 mysql grails

我是 Groovy & 的新手圣杯.我想提交解析 CSV 文件并导出到 MySQL 数据库的几个表中.我看过一些编码,但作为新手,这让我感到困惑.那么任何人都可以帮助我理解简单的 csv 文件解析并导出到 MySQL 数据库中.

I am newbie in Groovy & Grails. I want to submit parse CSV file and export into several tables of MySQL database. I have looked some coding but it was confusing for me as newbie. So can anybody help me in understanding simple csv file Parsing and exporting into MySQL database.

谢谢索努

推荐答案

Grails 一个引导程序,它在您的应用程序启动时运行.它的漂亮;你可以配置它在不同的环境中做不同的事情.

Grails a bootstrap process that runs whenever your app starts. Its nifty; you can configure it to do different things in different environments.

一种方法是在引导程序中执行以下操作:

One approach is to do the following in bootstrap:

1) 读取 csv 文件,随时创建域对象.
2)对于每个域对象,检查它是否存在,如果不存在你DomainObject.save()

1) Read the csv file, creating Domain objects as you go.
2) For each domain object, check to see if it exists, and if not do youDomainObject.save()

就是这样.

对于代码,类似

new File(filePath).splitEachLine(',') {fields ->
    def domainObject = new YouDomainObject(
        id: fields[0].trim(),
        name: fields[1].trim()
    )

    if (domainObject.hasErrors() || domainObject.save(flush: true) == null) {
        log.error("Could not import domainObject  ${domainObject.errors}")
    }

    log.debug("Importing domainObject  ${domainObject.toString()}")
}

相关文章