MySQLdb中文乱码问题的解决(Python)

    写了一个简单的脚本,将我的数据整理到Mysql中去。遇到了乱码问题,改了一下,很快就解决了。连接mysql时要注意注明是utf-8字符集,所有中文都要是utf-8,如果有GBK也要先转换成utf-8,把握这个原则,中文乱码问题是不会有的。

转换脚本如下:

#-*- coding: utf-8 -*-,
#coding = utf-8

import MySQLdb,os

def wgdata2DB():
    print "Convert weg game data to mysql"
    db=MySQLdb.connect(host='localhost',      #连接数据库
                      user='root',
                      passwd='123456',
                      db='testdb',
                      charset="utf8")     #这里要注明是utf8字符集,文件开头最好也加上utf-8的声明

    cursor=db.cursor()
      
    if os.path.exists('test.dat'):
        rFile = open('test.dat', 'r')
        lines = rFile.readlines()
        rFile.close()
        
        loop = 0
        for line in lines:
            print "handle line:%d" % (loop)
            myset = line.split(' ')
            
            sqlstr = "INSERT INTO wg_Content (type,title,url,speed,des,size) VALUES('%s','%s','%s','%s','%s','%s')" \
                %(myset[0],myset[1],myset[2],myset[3],myset[4],myset[5])
            cursor.execute(sqlstr)
            loop += 1            
            db.commit()
    cursor.close()
    db.close()

posted on 2012-02-21 21:07  Tony.Shao  阅读(465)  评论(0编辑  收藏  举报

导航