MySQL中文字符与Python中文字符

经过30个小时的coding,终于解决了编码问题.现在把过程和体会记录下来:P
MySQL 数据库方面:
数据库的创建支持UTF8:
CREATE DATABASE db_name DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
很多时候,默认的会选择COLLATE utf8_general_ci,这个对中文支持不好.我就是错在这里了。
Python 编码方面:
1指定文件编码是必须的:

#-*-coding:utf-8-*-


2某些环境下可以使用这个:

reload(sys);sys.setdefaultencoding('utf-8')


3python的字符串分为"unicode"和"str"
-1  str      是指带有编码的字符串
-2  unicode  是指不带有编码的字符串
这两个概念的相互转换是这样进行的:
str ------>   unicode --------> str
   decode             encode
   解码                    编码

举个最简单的例子:


 
引用
>>> a = '中' >>> a '\xd6\xd0' >>> b = u'中' >>> b
u'\u4e2d' [color=red][b]即保存'中'的gbk值做为b[/b]


根据上面的描述,b应该是不进行编码的a的值(反正a就是b带有gbk编码的值)
于是,我们可以得到
>>> a.decode( 'gbk' )
u'\u4e2d'

同样也可以得到
>>> b.encode( 'gbk' )
'\xd6\xd0'

所以一般的

xxx.decode('gbk').encode('utf-8')


4.MySQLdb操作

conn=MySQLdb.connect(host,usr,pwd,db,charset='utf8')




PHP读取操作:

<?php
$conn=mysql_connect($hostname='127.0.0.1',$username='root',$password='');
mysql_select_db('text');
mysql_query("set names 'utf8'");
$sql='select text from text where id = 1';
$result=mysql_query($sql,$conn);
while ($row = mysql_fetch_assoc($result)){
 print $row['text'];
}
?>



更多可以参考:
http://www.blogjava.net/vulcan/articles/160978.html
http://www.yuanma.org/data/2006/0907/article_1476.htm

你可能感兴趣的:(sql,PHP,.net,mysql,python)