如何使用mysql从csv文件中获取数据并保存到grails中?
例如: 我有一个像这样的CSV文件 我想把它保存到数据库中,上传CSV文件 这是我上传CSV文件的代码如何使用mysql从csv文件中获取数据并保存到grails中?,mysql,grails,csv,groovy,Mysql,Grails,Csv,Groovy,例如: 我有一个像这样的CSV文件 我想把它保存到数据库中,上传CSV文件 这是我上传CSV文件的代码 <input type="file" name="filecsv"/> <input type="button" class="upload" value="Upload onclick='location.href ="${createLink(url: [action: 'upload'])}"'/> 如何从CSV文件中获取数据并将
<input type="file" name="filecsv"/>
<input type="button" class="upload" value="Upload
onclick='location.href ="${createLink(url: [action: 'upload'])}"'/>
如何从CSV文件中获取数据并将其保存到数据库mysql中?您需要从传递的 你可以这样做
//Read the CSV file data excluding the header
filecsv.inputStream.toCsvReader(['skipLines':1]).eachLine { tokens ->
//parse the csv columns
def name= tokens[0].trim()
def class= tokens[1].trim()
def age = tokens[2].trim()
def phone = tokens[3].trim()
//assign the csv column values to domain object
City city = new City() // this is your domain/table that you used to insert csv data
city.name = name
city.class = class
city.age = age
if(!city.save(validate: true)){
city.errors.each {
log.debug(it)
}
}
}也许值得一看,“……但不是成功”是什么意思?你收到错误了吗?我已经编辑了我的帖子,我无法获取此路径“”,但是如果新文件('C:\\user\\desktop\\book1.csv'),它会成功。拆分链接(','){fields->2014-01-27 16:44:54047[http-8080-4]ERROR errors.grailExceptionResolver-没有方法的签名:org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper.getFile()适用于参数类型:(java.lang.String)值:[filecsv]可能的解决方案:getXML()、getAt(java.lang.String)、getAt(java.lang.String)、getLocale()、getJSON()、getHeader(java.lang.String)groovy.lang.MissingMethodException:没有方法的签名:org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper.getFile()你在GSP中使用的是
uploadForm
是吗?只有g:form中的这个我是指我答案的顶部…它需要以上传形式或多部分形式出现问题当前不是CSV解析,而是在控制器中获取多部分形式
<g:uploadForm action="upload">
<input type="file" name="filecsv" />
<input type="submit" />
</g:uploadForm>
def upload = {
request.getFile( 'filecsv' )
.inputStream
.splitEachLine(',') { fields ->
def city = new City( city: fields[0].trim(),
description: fields[1].trim() )
if (city.hasErrors() || city.save(flush: true) == null) {
log.error("Could not import domainObject ${city.errors}")
}
log.debug("Importing domainObject ${city.toString()}")
}
}
plugins {
//TODO other plugins
compile(":csv:0.3.1") // add this entry in BuildConfig.groovy
}
//Read the CSV file data excluding the header
filecsv.inputStream.toCsvReader(['skipLines':1]).eachLine { tokens ->
//parse the csv columns
def name= tokens[0].trim()
def class= tokens[1].trim()
def age = tokens[2].trim()
def phone = tokens[3].trim()
//assign the csv column values to domain object
City city = new City() // this is your domain/table that you used to insert csv data
city.name = name
city.class = class
city.age = age
if(!city.save(validate: true)){
city.errors.each {
log.debug(it)
}
}