1. 程式人生 > >Python MySQL - 進行資料查詢

Python MySQL - 進行資料查詢

#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'))