鍋氬ソ鍥涗歡浜嬶細
錛戯紝python婧愪唬鐮佷繚瀛樹負utf-8
錛掞紝鏁版嵁搴撳緩鎴恥tf-8
錛擄紝mysql榪炴帴璁劇疆涓簎tf-8
錛旓紝鏌ヨ緄愭灉涓殑鏂囨湰瀛楁鏄痷nicode鐨勶紝杞洖utf-8銆?br />
聽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聽=聽'濂戒漢涓涓?/span>'
21聽聽聽聽聽sql聽=聽'INSERT聽INTO聽utf8_table聽VALUES("%s",聽"%s")'%(key,聽value)
22聽聽聽聽聽cursor.execute(sql)聽聽聽聽聽聽 #娉ㄦ剰鏌愪簺鏃х増鏈殑mysql錛堝4.1.22浠ヤ笅錛夛紝mysql.character_set_name()鎬繪槸榪斿洖latin1錛屼細寮曡搗涔辯爜錛岄渶瑕佹敼涓?/span>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

]]>