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

        
        

 

posted @ 2018-11-14 11:09  子信风蓝蓝  阅读(2145)  评论(0编辑  收藏  举报