<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<title><![CDATA[运维进行时]]></title> 
<link>https://blog.liuts.com/index.php</link> 
<description><![CDATA[互联网运维与架构]]></description> 
<language>zh-cn</language> 
<copyright><![CDATA[运维进行时]]></copyright>
<item>
<link>https://blog.liuts.com/post//</link>
<title><![CDATA[python操作mysql中文问题小结]]></title> 
<author>root &lt;admin@yourname.com&gt;</author>
<category><![CDATA[Python]]></category>
<pubDate>Sat, 22 Sep 2007 06:44:01 +0000</pubDate> 
<guid>https://blog.liuts.com/post//</guid> 
<description>
<![CDATA[ 
	mysql 需要做的是：<br/><textarea name="code" class="sql" rows="15" cols="100">
CREATE DATABASE db_name DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
</textarea><br/>这是在创建数据库的时候需要是utf-8格式<br/>my.cnf或者my.ini<br/><div class="quote"><div class="quote-title">引用</div><div class="quote-content"><br/>[mysql]<br/>default-character-set = utf8<br/>default-character-set = utf8<br/>character-set-server = utf8<br/>collation-server = utf8_general_ci<br/>init_connect = 'SET collation_connection = utf8_general_ci'<br/>init_connect = 'SET NAMES utf8'<br/></div></div>我里面的配置文件是这样的<br/>python需要做的是：<br/>在前面加上这个<br/>#-*- encoding:utf-8 -*-<br/>有的环境可能需要加这个<br/>reload(sys)<br/>sys.setdefaultencoding('utf-8')<br/><br/>但是我的里面不需要这个也没问题<br/>最后别忘了在查询或者插入更新数据的时候在上面放这段代码<br/>curs.execute("SET NAMES 'gbk'")<br/>完整python代码如下：<br/><textarea name="code" class="python" rows="15" cols="100">
#-*- encoding:utf-8 -*-
#import sys
import MySQLdb

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

SERVER = 'localhost'
USERNAME = 'root'
PASSWD = 'root'
DB = 'newbbs'

conn = MySQLdb.connect(host=SERVER,db=DB,user=USERNAME,passwd=PASSWD)
curs = conn.cursor()
curs.execute("SET NAMES 'gbk'")
curs.execute('select * from cdb_members')

f = file("test.txt",'w')
while(1):
&nbsp;&nbsp;&nbsp;&nbsp;row = curs.fetchone()
&nbsp;&nbsp;&nbsp;&nbsp;if row ==None:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break
&nbsp;&nbsp;&nbsp;&nbsp;print "%s" % row[1]
&nbsp;&nbsp;&nbsp;&nbsp;f.writelines(row[1])
&nbsp;&nbsp; 
f.close()
curs.close()
conn.close()
</textarea><br/>Tags - <a href="https://blog.liuts.com/tags/python/" rel="tag">python</a> , <a href="https://blog.liuts.com/tags/mysql/" rel="tag">mysql</a> , <a href="https://blog.liuts.com/tags/%25E4%25B8%25AD%25E6%2596%2587/" rel="tag">中文</a>
]]>
</description>
</item><item>
<link>https://blog.liuts.com/post//#blogcomment</link>
<title><![CDATA[[评论] python操作mysql中文问题小结]]></title> 
<author> &lt;user@domain.com&gt;</author>
<category><![CDATA[评论]]></category>
<pubDate>Thu, 01 Jan 1970 00:00:00 +0000</pubDate> 
<guid>https://blog.liuts.com/post//#blogcomment</guid> 
<description>
<![CDATA[ 
	
]]>
</description>
</item>
</channel>
</rss>