使用Java Properties文件导致数据库乱码问题的解决

问题描述及解决方案

使用MyBatis操作数据库一直没问题,使用了Java Properties文件存放访问数据库的相关属性后,往数据库添加数据却出现了中文乱码。经排查,问题出在访问数据库的url上。我在xml文件中的url如下所示:

jdbc:mysql://localhost/college?useUnicode=true&characterEncoding=utf8

请注意,这里面的转义字符“&”代表字符“&”,是xml和html中的用法。我把这个url直接复制到了Java Properties文件中。但是在Properties文件中,是不认这个转义字符的。因此,后面的“characterEncoding=utf8”就无效了,自然会出现乱码。
找到原因后,解决方案也很简单,在Java Properties文件中不需要使用转义字符“&”,直接使用“&”即可,如下所示:

jdbc:mysql://localhost/college?useUnicode=true&characterEncoding=utf8

扩展知识

Java Properties文件不能输入中文的问题

在eclipse中将Java Properties文件的默认编码由ISO-8859-1改为UTF-8即可。点击Window->Preferences打开如下窗口进行设置:
在这里插入图片描述

property-placeholder读取Java Properties文件里的中文的方法

设置file-encoding=“utf8”,如下代码所示:

<context:property-placeholder location="classpath:db.properties" file-encoding="utf8"/>

猜你喜欢

转载自blog.csdn.net/m0_50384279/article/details/108485202