使用Python封装Mysql数据库的相关操作

引入第三方库

使用python连接数据库需要引入相应的第三方库

import pymysql

封装代码

class MysqlHelper:

    def __init__(self,host,port,user,database,password):
        self.host=host
        self.port=port
        self.user=user
        self.password=password
        self.database=database

    # 连接数据库
    def connect(self):
        self.conn=pymysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.password,database=self.database,charset='utf8')
        self.cursor=self.conn.cursor()

    # 关闭数据库
    def close(self):
        if self.conn is not None:
            self.conn.close()
    
    # 创建数据表
    def creaTable(self, sql):
        return self.edit(sql)

    # 提取出增删改的共同操作
    def edit(self,sql,sql_params=()):
        '''返回0:操作失败'''
        result=0
        if self.conn is None:
            print("请连接数据库")
            return

        try:
            result=self.cursor.execute(sql,sql_params)
            self.conn.commit()
        except Exception as e:
            print(e)
            self.conn.rollback()

        return result

    # 删除数据
    def delete(self,sql,sql_params=()):
        return self.edit(sql,sql_params)

    # 更新数据
    def update(self,sql,sql_params=()):
        return self.edit(sql,sql_params)

    # 插入数据
    def insert(self,sql,sql_params=()):
        return self.edit(sql,sql_params)

    # 获取多条数据
    def get_all(self,sql,sql_params=()):

        if self.conn is None:
            print("请连接数据库")
            return

        # 返回结果为一个数组
        result=()
        try:
            self.cursor.execute(sql,sql_params)
            result=self.cursor.fetchall()
        except Exception as e:
            print(e)
            self.conn.rollback()

        return result

    # 获取一条数据
    def get_one(self,sql,sql_params=()):

        if self.conn is None:
            print("请连接数据库")
            return

        result=()
        try:
            self.cursor.execute(sql,sql_params)
            result=self.cursor.fetchone()
        except Exception as e:
            print(e)
            self.conn.rollback()

        return result

测试

if __name__=='__main__':

    helper=MysqlHelper(host='hadoop101',port=3306,password='123456',user='root',database='ct')
    helper.connect()

    sql='''select * from ct_call'''
    result=helper.get_all(sql)
    for row in result:
        id=row[0]
        telid=row[1]
        dateid=row[2]
        sumcall=row[3]
        sumduration=row[4]

        print('id='+str(id)+','+
              'telid='+str(telid)+','+
              'dateid='+str(dateid)+','+
              'sumcall='+str(sumcall)+','+
              'sumduration='+str(sumduration))

    helper.close()

结果

使用Python封装Mysql数据库的相关操作_第1张图片

你可能感兴趣的:(#,python,数据库,mysql,python)