1. 程式人生 > >Python連線MySQL中有關中文亂碼的解決問題

Python連線MySQL中有關中文亂碼的解決問題

一、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()
     
    ifos.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