m
java使用utf8操作jdbc时数据库是latin1编码时乱码解决
1,正确配置jdbc的url
#6.0之后就是com.mysql.cj.jdbc.Driver了
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/loocode?user=root&password=123456&characterEncoding=Cp1252
characterEncoding=Cp1252意义:
jdbc会在执行SQL之前将sql语句字符串转换成对应的characterEncoding编码字节
为什么编码配置是Cp1252呢,可以看下jdbc官方文档:
able 5.3 MySQL to Java Encoding Name Translations
MySQL Character Set Name | Java-Style Character Encoding Name |
---|---|
ascii |
US-ASCII |
big5 |
Big5 |
gbk |
GBK |
sjis |
SJIS (or Cp932 or MS932 for MySQL Server < 4.1.11) |
cp932 |
Cp932 or MS932 (MySQL Server > 4.1.11) |
gb2312 |
EUC_CN |
ujis |
EUC_JP |
euckr |
EUC_KR |
latin1 |
Cp1252 |
latin2 |
ISO8859_2 |
greek |
ISO8859_7 |
hebrew |
ISO8859_8 |
cp866 |
Cp866 |
tis620 |
TIS620 |
cp1250 |
Cp1250 |
cp1251 |
Cp1251 |
cp1257 |
Cp1257 |
macroman |
MacRoman |
macce |
MacCentralEurope |
utf8 |
UTF-8 |
ucs2 |
UnicodeBig |
这个是java和mysql的编码对照表。
2,处理正确的字符串编码
java中不需要执行SET NAMES UTF8 这种语句.
在代码中字符串应该是使用GBK而非Cp1252.
this.jdbcTemplate = new JdbcTemplate(dataSource);
//int count = this.jdbcTemplate.queryForObject("SELECT count(*) FROM posts", Integer.class);
SimpleJdbcInsert insert = new SimpleJdbcInsert(this.jdbcTemplate); insert.withTableName("posts");
insert.usingColumns(new String[] {"user_id", "user_name"});
HashMap<String, Object> stringObjectHashMap = new HashMap<String, Object>();
stringObjectHashMap.put("user_id", 1);
//注意这句话的GBK,不能再用Cp1252
stringObjectHashMap.put("user_name", new String("你好测试".getBytes("GBK")));
insert.execute(stringObjectHashMap);