|
個(gè)人建議,數(shù)據(jù)庫(kù)字符集盡量使用utf8(utf-8),以使你的數(shù)據(jù)能很順利的實(shí)現(xiàn)遷移,因?yàn)閡tf8字符集是目前最適合于實(shí)現(xiàn)多種不同字符集之間的轉(zhuǎn)換的字符集,盡管你在命令行工具上無(wú)法正確查看數(shù)據(jù)庫(kù)中的內(nèi)容,我依然強(qiáng)烈建議使用utf8作為默認(rèn)字符集. 接下來(lái)是完整的一個(gè)例子: 1.創(chuàng)建數(shù)據(jù)庫(kù)表 mysql>CREATE DATABASE IF NOT EXISTS my_db default charset utf8 COLLATE utf8_general_ci; #注意后面這句話 "COLLATE utf8_general_ci",大致意思是在排序時(shí)根據(jù)utf8編碼格式來(lái)排序 #那么在這個(gè)數(shù)據(jù)庫(kù)下創(chuàng)建的所有數(shù)據(jù)表的默認(rèn)字符集都會(huì)是utf8了 mysql>create table my_table (name varchar(20) not null default '')type=myisam default charset utf8; #這句話就是創(chuàng)建一個(gè)表了,制定默認(rèn)字符集為utf8 2.寫數(shù)據(jù) 通過(guò)php直接插入數(shù)據(jù): <?php mysql_connect('localhost','user','password'); mysql_select_db('my_db'); //請(qǐng)注意,這步很關(guān)鍵,如果沒(méi)有這步,所有的數(shù)據(jù)讀寫都會(huì)不正確的 //它的作用是設(shè)置本次數(shù)據(jù)庫(kù)聯(lián)接過(guò)程中,數(shù)據(jù)傳輸?shù)哪J(rèn)字符集 mysql_query("set names utf8;"); //必須將gb2312(本地編碼)轉(zhuǎn)換成utf-8,也可以使用iconv()函數(shù) mysql_query(mb_convet_encoding("insert into my_table values('測(cè)試');", "utf-8", "gb2312")); ?> 通過(guò)頁(yè)面提交插入數(shù)據(jù): <?php //輸出本頁(yè)編碼為utf-8 header("content-type:text/html; charset=utf-8"); mysql_connect('localhost','user','password'); mysql_select_db('my_db'); if(isset($_REQUEST['name')) { //由于上面已經(jīng)指定本頁(yè)字符集為utf-8了,因此無(wú)需轉(zhuǎn)換編碼 mysql_query(sprintf("insert into my_table values('%s');", $_REQUEST['name'])); } $q = mysql_query("select * from my_table"); while($r = mysql_fetch_row($q)) { print_r($r); } ?> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <form action="" method="post"> <input type="text" name="name" value=""> <input type="submit" value='submit'> </form> 自此,使用utf8字符集的完整的例子結(jié)束了. 如果你想使用gb2312編碼,那么建議你使用latin1作為數(shù)據(jù)表的默認(rèn)字符集,這樣就能直接用中文在命令行工具中插入數(shù)據(jù),并且可以直接顯示出來(lái).而不要使用gb2312或者gbk等字符集,如果擔(dān)心查詢排序等問(wèn)題,可以使用binary屬性約束,例如: create table my_table ( name varchar(20) binary not null default '')type=myisam default charset latin1; 附:舊數(shù)據(jù)升級(jí)辦法 以原來(lái)的字符集為latin1為例,升級(jí)成為utf8的字符集。原來(lái)的表: old_table (default charset=latin1),新表:new_table(default charset=utf8)。 第一步:導(dǎo)出舊數(shù)據(jù) mysqldump --default-character-set=latin1 -hlocalhost -uroot -B my_db --tables old_table > old.sql 第二步:轉(zhuǎn)換編碼 iconv -t utf-8 -f gb2312 -c old.sql > new.sql 在這里,假定原來(lái)的數(shù)據(jù)默認(rèn)是gb2312編碼。 第三步:導(dǎo)入 修改old.sql,增加一條sql語(yǔ)句: "SET NAMES utf8;",保存。 mysql -hlocalhost -uroot my_db < new.sql
信息發(fā)布:廣州名易軟件有限公司 http://www.jetlc.com
|