python操作数据库取字段中的中文的时候,如果用CMD打印可能出现UNICODE的编码

例如:我们要取下面中的‘忻贵春’

代码:

#coding = utf-8
import MySQLdb
conn = MySQLdb.connect(
    host = 'localhost',
    port = 3306,
    user = 'root',
    passwd = '111111',
    db = 'test',
    charset = "utf8")
cursor = conn.cursor()
print cursor
print type(cursor)

cursor.execute("select NAME from test1 where sex='男' ")
while 1:
    res = cursor.fetchone()
    if res is None:
        #取所以结果,为空时跳出循环
        break
    print res
    
cursor.close()
conn.commit()
conn.close()
print u'插入忻贵春的信息成功!'

此时,无需惊慌,只需要改一下编码即可

标红处改为  :   print res[0].encode('gbk')   

再次打印如下: