Java JDBC 字符编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3040597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:54:50  来源:igfitidea点击:

JDBC character encoding

javamysqljdbccharacter-encoding

提问by Daniel Szalay

I have a Java Web application running on GlassFish 3 and JPA (EclipseLink) on MySQL. The problem I'm facing is that if I'm saving entities to the database with the update()method, Stringfields lose integrity; '?'is shown instead of some characters.

我有一个运行在 GlassFish 3 上的 Java Web 应用程序和 MySQL 上的 JPA (EclipseLink)。我面临的问题是,如果我使用该update()方法将实体保存到数据库中,String字段将失去完整性;'?'显示而不是某些字符。

The server, pages and database are configured to use UTF-8.

服务器、页面和数据库配置为使用UTF-8.

After I post form data, the next page shows the data correctly. Furthermore it "seems" in NetBeans debug that the Stringproperty of the current entity stores the correct value too. Dunno if NetBeans debug can be trusted; might be that it decodes correctly, however it's incorrect.

发布表单数据后,下一页正确显示数据。此外,在 NetBeans 调试中“似乎”String当前实体的属性也存储了正确的值。不知道 NetBeans 调试是否可信;可能是它解码正确,但它是不正确的。

采纳答案by Bozho

It's JDBC, not JPA that determines the encoding:

决定编码的是 JDBC,而不是 JPA:

jdbc:mysql://localhost:3306/administer?characterEncoding=utf8

回答by Daniel Szalay

I solved it with the following: I used the GlassFish admin interface to add this property to my connection pool's settings:

我使用以下方法解决了这个问题:我使用 GlassFish 管理界面将此属性添加到我的连接池设置中:

characterEncoding = UTF-8

字符编码 = UTF-8

回答by bentzy

I had to add useUnicode=true as well, so I had to concat the parameters with '&' so it looks like this:

我还必须添加 useUnicode=true ,所以我必须用 '&' 连接参数,所以它看起来像这样:

jdbc:mysql://127.0.0.1:3306/warranteer?useUnicode=true&characterEncoding=UTF-8

If you're using maven profiles to set the MySQL URL, like me, make sure you put &instead &because maven unescape the url when writing the persistence.xml file to classes folder.

如果您像我一样使用 Maven 配置文件来设置 MySQL URL,请确保&改为使用 Maven,&因为在将 persistence.xml 文件写入 classes 文件夹时,Maven 会取消对 url 的转义。

回答by fjjiaboming

New version JDBC driver auto detect the characterEncoding. You do not need to set it explicitly.

新版本 JDBC 驱动程序自动检测字符编码。您不需要明确设置它。