#coding=utf-8 import mysql.connector import importlib import sys # reload(sys) # sys.setdefaultencoding('utf-8') #鏈接數據庫的信息 class ConnectionMysql(object): __config = { 'host':'115.xx.10.121', 'port':'3306', 'user':'root', 'password':'xxxxx8Z6XPXbvos', 'database':'xxxx_site', 'charset':'utf8', } def __init__(self): try: self.conn = mysql.connector.connect(**ConnectionMysql.__config) except mysql.connector.Error as e: self.conn = None self.cursor = None def connectdatabase(self): pass #查詢數據 def selectdatabase(self,sql): self.cursor = self.conn.cursor(buffered=True) #執行sql語句 self.cursor.execute(sql) # fetchall() 獲取全部記錄 dataslist = self.cursor.fetchall() dataslists = [] for datas in dataslist: for data in datas: if data==None: dataslists.append(data) else: #dataslists.append(data.decode('utf-8')) dataslists.append(data) return dataslists def closedatabase(self): try: print '關閉數據庫中。。' self.cursor.close()#關閉標記位 self.conn.close()#關閉數據庫連接 print '數據庫已關閉' except mysql.connector.Error as e: raise Exception('關閉數據庫失敗,%s'%(str(e))) if __name__ == '__main__': conn = ConnectionMysql() conn.connectdatabase() dataslist = conn.selectdatabase('select title from site_basic_info') #repr(dataslist).decode('unicode-escape') 解決中文編碼問題 print(repr(dataslist).decode('unicode-escape'))