解决乱码问题一个原则:存取系统使用一致的编码规则。
多使用mysql的原生命令行,这样才能做更多的事情。
确认应用系统需要使用的编码
java的默认编码是跟随系统的,有的说是默认UNICode,在java中可以使用 String defaultCharsetName=Charset.defaultCharset().displayName();显示编码。
确认并设置MySql的数据库的编码
1. 显示编码,简单的方法命令是:status; 或者mysql> SHOW VARIABLES LIKE 'character%';
mysql> status
--------------
C:Program Files (x86)MySQLMySQL Server 5.0inmysql.exe Ver 14.12 Distrib 5
.0.67, for Win32 (ia32)
Connection id: 3
Current database:
Current user: root@localhost
SSL: Not in use
Using delimiter: ;
Server version: 5.0.67-community-nt MySQL Community Edition (GPL)
Protocol version: 10
Connection: localhost via TCP/IP
Server characterset: gbk
Db characterset: gbk
Client characterset: gbk
Conn. characterset: gbk
TCP port: 3306
Uptime: 12 min 59 sec
Threads: 3 Questions: 32 Slow queries: 0 Opens: 32 Flush tables: 1 Open tab
les: 26 Queries per second avg: 0.041
--------------
2. 修改编码
确保万无一失必须所有的都设置成需要的字符,这里我们以utf8为例子。
2.1 my.ini配置文件中的修改,(命令行中使用set设置的重启服务后会失效),各个标签下面的都需要修改:
C:Program Files (x86)MySQLMySQL Server 5.0my.ini
[client]
default-character-set=utf8
[mysql]
default-character-set=utf8
[mysqld]
default-character-set=utf8
2.2 Server characterset是没办法在配置文件中修改的,但也不用重装数据库,只需要重新启动配置程序MySQLInstanceConfig.exe就可以了。
C:Program Files (x86)MySQLMySQL Server 5.0inMySQLInstanceConfig.exe
在选择编码的地方选择utf8就可以了,默认的是Latin1。选的二个或者第三个,第二个默认就是UTF8, 第三个手动选UTF8.
重启mysql服务
cmd下:
net stop mysql
net start mysql
mysql> use qba_db;
Database changed
mysql> status;
--------------
C:Program Files (x86)MySQLMySQL Server 5.0inmysql.exe Ver 14.12 Distrib 5
.0.67, for Win32 (ia32)
Connection id: 168
Current database: qba_db
Current user: root@localhost
SSL: Not in use
Using delimiter: ;
Server version: 5.0.67-community-nt MySQL Community Edition (GPL)
Protocol version: 10
Connection: localhost via TCP/IP
Server characterset: utf8
Db characterset: utf8
Client characterset: utf8
Conn. characterset: utf8
TCP port: 3306
Uptime: 20 days 11 hours 4 min 19 sec
Threads: 5 Questions: 3224 Slow queries: 0 Opens: 151 Flush tables: 1 Open
tables: 0 Queries per second avg: 0.002
--------------
SHOW VARIABLES LIKE 'character%';
-- Variable_name Value
-- character_set_client latin1
-- character_set_connection latin1
-- character_set_database utf8
-- character_set_filesystem binary
-- character_set_results latin1
-- character_set_server gbk
-- character_set_system utf8
-- character_sets_dir D:Program FilesphpStudyMySQLsharecharsets
set character_set_client=utf8;
set character_set_connection=utf8;
set character_set_database=utf8;
set character_set_results=utf8;
set character_set_server=utf8;
set character_set_system=utf8;
-- set collation_connection=utf8;
-- set collation_database=utf8;
-- set collation_server=utf8;