将pymysql封装成一个类

import pymysql

# 定义一个数据库相关的配置项
DB_CONFIG = {'host': '127.0.0.1',
             'user': 'root',
             'password': '123',
             'port': 3306,
             'db': 'django',
             'charset': 'utf8'
             }


class SQLManager(object):

    # 连接数据库
    # 将conn,cursor作为类的属性,通过connect方法触发生成
    def __init__(self):
        self.conn = None
        self.cursor = None
        self.connect()

    def connect(self):
        self.conn = pymysql.connect(
            host=DB_CONFIG['host'],
            port=DB_CONFIG['port'],
            user=DB_CONFIG['user'],
            password=DB_CONFIG['password'],
            db=DB_CONFIG['db'],
            charset=DB_CONFIG['charset']
        )

        self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

    # 查询多条数据
    def get_all(self, sql, *args):
        self.cursor.execute(sql, *args)
        return self.cursor.fetchall()

    # 查询一条数据
    def get_one(self, sql, *args):
        print(sql)
        print(args)
        self.cursor.execute(sql, *args)
        return self.cursor.fetchone()

    # 修改数据
    def modify(self, sql, *args):
        print(args)
        self.cursor.execute(sql, args)
        self.conn.commit()

    # 关闭数据库cursor和连接
    def close(self):
        self.cursor.close()
        self.conn.close()


if __name__ == '__main__':
    # conn = pymysql.connect(host='127.0.0.1', user='root', password='123', db='django', charset='utf8')
    # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    #
    # sql = "select * from classes where id=%s"
    #
    # cursor.execute(sql,1)
    # classes = cursor.fetchone()
    # print(classes)
    db = SQLManager()
    # print(db.get_all("select id,name from classes"))
    # print(db.get_one("select * from %s" % ("classes") + " where id=%s", 1))
    # db.modify("insert into classes (name) values (%s)",'脱产16期')
    # db.modify("delete from classes where id=%s",10)
    db.modify("update classes set name=%s where id=%s", '脱产160期', 19)

你可能感兴趣的:(将pymysql封装成一个类)