• 做好四件事:
1,python源代碼保存為utf-8
2,數(shù)據(jù)庫建成utf-8
3,mysql連接設(shè)置為utf-8
4,查詢結(jié)果中的文本字段是unicode的,轉(zhuǎn)回utf-8。

  • 總結(jié)性的示例代碼:
?1?#!/usr/bin/env?python
?2?#-*-?coding:?utf-8?-*-
?3?
?4?import?MySQLdb
?5?
?6?if?__name__?==?'__main__':
?7?????mysql?=?MySQLdb.connect(host='localhost',?user='root',?passwd='123456',?charset='utf8')
?8?????cursor?=?mysql.cursor()
?9?????cursor.execute('SET?NAMES?UTF8')
10?????sql?=?'DROP?DATABASE?IF?EXISTS?mysqldb_utf8_test'
11?????cursor.execute(sql)
12?????sql?=?'CREATE?DATABASE?mysqldb_utf8_test?DEFAULT?CHARACTER?SET?utf8?COLLATE?utf8_general_ci'
13?????cursor.execute(sql)
14?????mysql?=?MySQLdb.connect(host='localhost',?user='root',?passwd='123456',?db='mysqldb_utf8_test',?charset='utf8')
15?????cursor?=?mysql.cursor()
16?????cursor.execute('SET?NAMES?UTF8')
17?????sql?=?'CREATE?TABLE?utf8_table(key_field?VARCHAR(32)?NOT?NULL,?value_field?VARCHAR(255)?NOT?NULL)'
18?????cursor.execute(sql)
19?????key?=?'tangxinfa'
20?????value?=?'好人一個'
21?????sql?=?'INSERT?INTO?utf8_table?VALUES("%s",?"%s")'%(key,?value)
22?????cursor.execute(sql)?????? #注意某些舊版本的mysql(如4.1.22以下),mysql.character_set_name()總是返回latin1,會引起亂碼,需要改為cursor.execute('INSERT?INTO?utf8_table?VALUES("%s",?"%s")', (key,?value))
23?????sql?=?'select?*?from?utf8_table'
24?????cursor.execute(sql)
25?????for?record?in?cursor.fetchall():
26?????????for?item?in?record:
27?????????????print?item.encode('utf8')

  • 參考
http://mysql-python.sourceforge.net/MySQLdb.html
http://bbs.phpchina.com/viewthread.php?tid=13861
http://hi.baidu.com/ak456/blog/item/c318502394aa20569922ed7b.html