1. 程式人生 > >python MySQL database 訪問處理(含中文字元處理)例項

python MySQL database 訪問處理(含中文字元處理)例項

直接上程式碼:

#!/usr/bin/env python                                                                         
# encoding: utf-8                                                                             
import sys, getopt
import string
import MySQLdb
import sys
reload(sys)
sys.setdefaultencoding('utf-8')




if __name__ == '__main__':
        opts,args = getopt.getopt(sys.argv[1:], 'hp:u:d:U:')
        user=""
        passwd=""
        database=""
        url=""    
        for op, value in opts:                                                                
                if op == "-u": 
                        user = value                                                          
                        print user                                                            
                elif op == "-p": 
                        passwd = value                                                        
                        print passwd                                                          
                elif op =="-d":
                        database = value                                                                                  
                        print database                                                        
                elif op =="-U":
                        url = value                                                           
                        print url                                                             
                else:
                        print "wrong usage!\n -u user -p passwd  -d database -U url"
                        sys.exit()

        db = MySQLdb.connect(url, user,passwd, database, charset='utf8' )
        cursor = db.cursor()
        sql = 'select wave_name,dialog_text from nlg_dialog where pid=914001896'
        cursor.execute(sql)
        results = cursor.fetchall()
        print r'voiceMap={'
        for i in range(0, len(results)):
                if(results[i][0] !="tts"):
                        print ("[\"%s\"]=\"%s\"," %(results[i][0],results[i][1]))
        print r'}'
                #fo.write(results[i][0])
        db.close()

上面的encoding相關的code是為了處理中文字元