【Python】公共类-获取MySQL数据

# -*- coding: UTF8 -*-
__author__ = 'zhangh'

import pymysql

class Conn2MySQL(object):
    def __init__(self, host, user, password, port):
        """
        connect to mysql
        get mysql data
        :return: tuple
        """
        self.host     = host
        self.user     = user
        self.port     = port
        self.passwd   = password

    def get_data(self, sql):
        connection = pymysql.connect(host=self.host, user =self.user, passwd=self.passwd, port=self.port, charset="utf8")
        try:
            with connection.cursor() as cursor:
                cursor.execute(sql)
                result = cursor.fetchall()
                connection.commit()
                return result
        except pymysql.Error as e:
            return e
        finally:
            connection.close()

# sql = "select id from dbcm.tmp where id=1"
# conn = Conn2MySQL(host='172.19.44.12', user='mysqladmin', password='mysqladmin', port=3306)
# result = conn.get_data(sql)

 

posted @ 2020-01-26 17:46  巧克力脆片  阅读(267)  评论(0编辑  收藏  举报