首页 > 数据库技术 > 详细

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

时间:2020-01-26 18:30:35      阅读:96      评论:0      收藏:0      [点我收藏+]
# -*- 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)

 

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

原文:https://www.cnblogs.com/haohaozhang/p/12234510.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!