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

时间:2021-09-05 02:22:01

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