码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2020-01-26 18:58:47      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:turn   fetchall   span   erro   host   min   word   com   col   

# -*- 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数据

标签:turn   fetchall   span   erro   host   min   word   com   col   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!