zoukankan      html  css  js  c++  java
  • day92-django-pymysql操作mysql封装之优化版,自定义的sqlhelper.py模块

    import pymysql
    
    #把pymysql操作mysql的代码封装到类里面,可以实现一次连接,多次操作。
    #前面代码是多次连接,多次操作,频繁连接会拖累操作数据库的速度。
    #一个self对象贯穿整个类,每一个方法里面都是同一个self对象。
    class Sqlhelper(): #实例化的时候,自动启动__init__方法来调用connect方法来连接数据库。 #所以在类的外面,不需要使用对象.connect()来连接。 def __init__(self): self.connect() #连接数据库,创建cursor光标对象。 def connect(self): self.conn = pymysql.connect(host='localhost',port=3306,user='root',password='123',database='django_test',charset='utf8') self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor) #查询,返回[dict1,dict2,.....] def get_list(self,sql,args): self.cursor.execute(sql,args) result = self.cursor.fetchall() return result # 查询,返回dict def get_one(self,sql,args): self.cursor.execute(sql,args) result = self.cursor.fetchone() return result #增删改操作,不需要返回值,要提交 def modify(self,sql,args): self.cursor.execute(sql,args) self.conn.commit() #增删改的批量操作,args是[('tom',1),('marry',2)] def multiple_modify(self,sql,args): # self.cursor.executemany(insert into students(name,class_id) values(%s,%s), [('tom',1),('marry',2)]) self.cursor.executemany(sql,args) self.conn.commit() #用于数据插入操作,并且返回(最后一行)当前行的id,因为数据库的id设置了主键自增。 def create(self,sql,args): self.cursor.execute(sql,args) self.conn.commit() return self.cursor.lastrowid #关闭关闭对象,关闭连接 def close(self): self.cursor.close() self.conn.close() # 调用: # 先实例化 # obj = sqlhelper.Sqlhelper() # 对象.方法(实参) # obj.modify(sql,args) #速记:以前是模块.方法,现在是模块.类.方法
  • 相关阅读:
    关于值传递和引用传递
    单例设计模式(创建型模式)
    逻辑分页和物理分页
    java基本数据类型
    Keepalived笔记
    lvs,HAProxy,nginx简单笔记
    限流, 熔断,降级笔记
    redis事务之watch
    Redis-Sentinel
    正式入驻博客园
  • 原文地址:https://www.cnblogs.com/python-daxiong/p/12668028.html
Copyright © 2011-2022 走看看