将文本直接从文本文件保存到数据库时,UncategorizedSQLException Incorrect String value 错误?

UncategorizedSQLException Incorrect String value error when saving a text directly from text file to database?

我导入了一个文件并阅读了它的内容。然后我将内容直接保存到数据库中。代码示例如下

def file = request.getFile('file')
if (file.empty) {
    flash.message = "File cannot be empty"
    return
}
String content = new String(file.getBytes())
Product product = new Product()
product.description = content
product.save(flush:true, failOnError:true)

保存失败并抛出以下错误。

org.springframework.jdbc.UncategorizedSQLException: Hibernate operation: could not insert: [Product]; uncategorized SQLException for SQL [...]; SQL state [HY000]; error code [1366]; Incorrect string value: '\xEF\xBB\xBFNan' for column 'product_description' at row 1; nested exception is java.sql.SQLException: Incorrect string value: '\xEF\xBB\xBFNan' for column 'product_description' at row 1

我猜这个问题与编码有关。我想知道在将内容保存到数据库之前是否需要对从文件导入的内容做些什么。

感谢任何帮助。谢谢!

请看下方错误画面

更新:

这是实际代码

def uploadRegistrations() {


    def file = request.getFile('file')

    if (file.empty) {
        flash.message = "File cannot be empty"
        return
    }

    String content = new String(file.getInputStream().getText('UTF-8'))

    def id = params['id']    

    def event = CompositeEvent.get(id.toLong())



    def reg = new RaceRegistration(race: event.races[0], compositeEvent: event, raceParticipant: new EmbeddedRaceParticipant(
            firstName: content.split(',')[0],
            lastName: "none",
            gender: Gender.MALE

    ),
            waiver: Waiver.getInstance(event),
            status: EntityStatus.ACTIVE

    )

    reg.save(flush: true, failOnError: true)

重要的部分是内容用于 RaceRegistration 域的名字。

关键在

java.sql.SQLException: Incorrect string value: '\xEF\xBB\xBFNan'

\xEF\xBB\xBFEFBBBFByte order mark (BOM) 用于 UTF-8 编码

而且您的数据库似乎阻止您进行错误的从流到字符串的编码转换

实际上文本文件中的前 2-5 个字节可以显示用于保存文件的 unicode 编码(UTF-8、UTF-16、UTF-32,...)。

如果你需要读取不同编码的文本文件,我建议你使用BOMInputStream from apache commons io

像这样:

import org.apache.commons.io.input.BOMInputStream
...

BOMInputStream bis = new BOMInputStream(file.getInputStream())
//get charset from stream or default if not defined
String charset =  bis.getBOM()?.getCharsetName() ?: "UTF-8" 
String content = bis.getText(charset)