用PyDev开发数据库读写程序,数据库是mysql,用utf-8字符集。

有开发者在提到:

“我用了下面几个措施,保证MySQL的输出没有乱码:

 1 Python文件设置编码 utf-8 (文件前面加上 #encoding=utf-8)

    2 MySQL数据库charset=utf-8 

    3 Python连接MySQL是加上参数 charset=utf8 

    4 设置Python的默认编码为 utf-8 (sys.setdefaultencoding(utf-8)

实践证明,第4条不要去做,在PyDev中也提醒sys中不再支持setdefaultencoding(我用的是Python2.7)

Just don't. If you change the default encoding you are going to break 
important data structures like dicts in a subtle and hard to detect way. 
If your application needs to change the default encoding, it's broken. 
The function is removed for a very good reaso. 


总之,python社区不再推荐对默认编码进行修改,这样会引发很多很难追踪的问题。

这样,只用前面提到的三条就可以搞定中文乱码问题。

    1 Python文件设置编码 utf-8 (文件前面加上 #encoding=utf-8)
    2 MySQL数据库charset=utf-8 
    3 Python连接MySQL是加上参数 charset=utf8 

#coding=utf-8
import logging
import os
import MySQLdb

conn=MySQLdb.Connect(host="localhost",user="root",passwd="root",db="tw",charset="utf8")

#select all tuples in any table which exists in the new database
def selectAllFromTable(conn,tableName):
    cursor =conn.cursor()
    sql ="select * from %s" % tableName
    cursor.execute(sql)
    while(1):
        row=cursor.fetchone()
        if row==None:
            break
        logger.debug(row)
    logger.debug("row number is %d" % cursor.rowcount)
def setLogger():
    # 创建一个logger,可以考虑如何将它封装
    logger = logging.getLogger('mylogger')
    logger.setLevel(logging.DEBUG)
    
    # 创建一个handler,用于写入日志文件
    fh = logging.FileHandler(os.path.join(os.getcwd(), 'log.txt'))
    fh.setLevel(logging.DEBUG)
    
    # 再创建一个handler,用于输出到控制台
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    
    # 定义handler的输出格式
    formatter = logging.Formatter('%(asctime)s - %(module)s.%(funcName)s.%(lineno)d - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)
    
    # 给logger添加handler
    logger.addHandler(fh)
    logger.addHandler(ch)
    
    # 记录一条日志
    logger.info('hello world, i\'m log helper in python, may i help you')
    return logger

#return sql
def generateFromSQL(tableName,listColumn):
    sql="select "
    length=len(listColumn)
    i=0
    for column in listColumn:
        if(i!=(length-1)):
            sql=sql+column+","
        else:
            sql=sql+column+" from "
        i=i+1
    sql=sql+tableName
    logger.info(sql)
    return sql
    
#对单个表插入一个元组,其定义有
def insertOneData(conn,tableName,listColumn,lData):
    cursor=conn.cursor()
    sql="insert into "+tableName+"("
    i=0
    length=len(listColumn)
    for column in listColumn:
        if(i!=(length-1)):
            sql=sql+column+","
        else:
            sql=sql+column+") values("
        i=i+1
    for i in range(0,length):
        if(i!=(length-1)):
            sql=sql+"%s,"
        else:
            sql=sql+"%s);"
    logger.info(sql)
    logger.info(lData)
    cursor.execute(sql,lData);
    conn.commit()

if __name__ == '__main__':
    logger=setLogger()