1,python源代码保存为utf-8
2,数据库建成utf-8
3,mysql连接设置为utf-8
4,查询結果中的文本字段是unicode的,转回utf-8。
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.htmlhttp://bbs.phpchina.com/viewthread.php?tid=13861http://hi.baidu.com/ak456/blog/item/c318502394aa20569922ed7b.html