python 访问数据库

半城伤御伤魂 提交于 2020-01-21 14:12:34
# -*- coding: utf-8 -*-
import pymysql

"""
数据库操作工具类
"""


class MySQLClient():
    def __init__(self, host="host", user="root", password="password", db="db"):
        self.connect = pymysql.connect(host=host, port=3306, user=user, passwd=password, db=db, charset='utf8')
        self.cursor = self.connect.cursor(pymysql.cursors.DictCursor)

    def queryOneData(self, sql):
        try:
            self.cursor.execute(sql)
        except Exception as e:
            print(e)
        else:
            return self.cursor.fetchone()

    def queryDataList(self, sql):
        try:
            self.cursor.execute(sql)
        except Exception as e:
            print(e)
        else:
            return self.cursor.fetchall()

    def insertOneData(self, sql):
        try:
            self.cursor.execute(sql)
            self.connect.commit()
        except Exception as e:
            self.connect.rollback()
            print(e)

    def updateData(self, sql):
        try:
            self.cursor.execute(sql)
            self.connect.commit()
        except Exception as e:
            self.connect.rollback()
            print(e)

    def deleteData(self, sql):
        try:
            self.cursor.execute(sql)
            self.connect.commit()
        except Exception as e:
            self.connect.rollback()
            print(e)

    def close(self):
        self.cursor.close()
        self.connect.close()

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!