2014-01-13 63 views
2
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,我做錯了什麼?爲什麼java字符串沒有在MYSQL中保存爲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/ | 
+--------------------------+----------------------------+ 

回答

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"); 
+0

改變了所有,但我仍然得到那糟糕的編碼字符串 –

+0

你重新啓動MySQL服務器? –

+0

是的,編輯的問題... –

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以獲得更多幫助。

+0

試過,但我stll得到不好的編碼:( –

+0

嘗試重新啓動您的mysql服務。 – wangdq

+1

mysqld重新啓動,沒有改變 –

相關問題