gpt4 book ai didi

mysql - UncategorizedSQLException 将文本直接从文本文件保存到数据库时出现不正确的字符串值错误?

转载 作者:行者123 更新时间:2023-11-29 09:54:18 24 4
gpt4 key购买 nike

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

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

我猜测问题与编码有关。我想知道在将内容保存到数据库之前是否需要对从文件导入的内容执行某些操作。

我很感激任何帮助。谢谢!

请查看错误屏幕下方

enter image description here

更新:

这是实际的代码

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)

关于mysql - UncategorizedSQLException 将文本直接从文本文件保存到数据库时出现不正确的字符串值错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54167024/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com