Parse CSV and export into Mysql database in Grails

后端 未结 2 624
不思量自难忘°
不思量自难忘° 2021-01-15 10:15

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

相关标签:
2条回答
  • 2021-01-15 11:14

    Since Groovy integrates with Java you can also use a Java library called opencsv to read the CSV if you're more comfortable with that.

    0 讨论(0)
  • 2021-01-15 11:15

    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) 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()

    thats it.

    for code, something like

    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()}")
    }
    
    0 讨论(0)
提交回复
热议问题