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,我做错了什么?
+--------------------------+----------------------------+
| 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/ |
+--------------------------+----------------------------+
答案 0 :(得分:1)
通常,MySQL附带一个预定义系统变量列表。如果要列出它们,可以打开MySQL提示符并键入:
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 文件并添加以下行:
[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服务器时,您会注意到差异。
修改强>:
您可以像这样设置JDBC DriverManager
的编码:
DriverManager.getConnection("jdbc:mysql://" + host + "/" + db + "?useUnicode=true&"
+ "user=" + login + "&password=" + password + "&characterEncoding=utf8");
答案 1 :(得分:0)
除了在java jdbc中设置连接字符串外,还有另一种更改mysql字符集的方法:
1)在创建数据库和表时指定utf8
//database
CREATE DATABASE IF NOT EXISTS databasename
default charset utf8
COLLATE utf8_general_ci;
//table
CREATE TABLE `Extenics`.`BE_headset` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8;
2)或在创建后改变它(我不鼓励这样做)
ALTER DATABASE db_name
[[DEFAULT] CHARACTER SET charset_name]
[[DEFAULT] COLLATE collation_name]
请参阅mysql以获取更多帮助。