为什么java字符串不能在MYSQL中保存为UTF-8? [英] Why java strings are not saved as UTF-8 in MYSQL?
问题描述
message = new String(("round " + id).getBytes("UTF-8"));
conn = DriverManager.getConnection("jdbc:mysql://" + host + "/" + db + "?useUnicode=true&characterEncoding=UTF-8&"
+ "user=" + login + "&password=" + password);
当我插入数据库时,编码为 UTF-8 CI
,得到这样的 179
,java文件编码是utf-8,我做错了什么?
When I make an insert into the database which encoding is UTF-8 CI
, get something like this �������������������� 179
, the java file encoding is utf-8, what I'am doing wrong?
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
推荐答案
通常,MySQL附带一个预定义的系统变量列表。如果你想列出它们,你可以打开MySQL提示符并键入:
Generally, MySQL comes with a list of predefined system variables. If you want to list them, you can open the MySQL prompt and type:
mysql> SHOW VARIABLES LIKE 'char%';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | latin1 |
| character_set_connection | latin1 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | latin1 |
| character_set_server | latin1 |
| character_set_system | latin1 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
如图所示,MySQL的默认编码是 latin1
。要更改它,您需要修改 my.cnf 文件并添加以下行:
As shown, MySQL's default encoding is latin1
. In order to change it, you need to edit a bit your my.cnf file and add the following lines:
[client]
default-character-set=utf8
[mysql]
default-character-set=utf8
[mysqld]
collation-server = utf8_unicode_ci
init-connect='SET NAMES utf8'
character-set-server = utf8
配置 my.cnf 文件并重新启动MySQL服务器时,您会注意到区别。
When you configure the my.cnf file and restart the MySQL server, you'll note the difference.
编辑:
您可以像下面这样为JDBC的 DriverManager
p>
Edit:
You can set the encoding for the JDBC's DriverManager
like this:
DriverManager.getConnection("jdbc:mysql://" + host + "/" + db + "?useUnicode=true&"
+ "user=" + login + "&password=" + password + "&characterEncoding=utf8");
这篇关于为什么java字符串不能在MYSQL中保存为UTF-8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!