封装Python操作mysql类

#封装python操作mysql的类
#encoding=utf-8
import pymysql
import time
class pymysql_class():
#初始化,规定对象所拥有的属性
def init(self,host = “127.0.0.1”,user= “root”,
passwd=“root”,db=“test”,charset=“utf8”):
self.host = host
self.user = user
self.passwd = passwd
self.db = db
self.charset= charset
self.conn = pymysql.connect(host = self.host,user=self.user,
passwd = passwd,db =db,charset = charset)
self.cursor = self.conn.cursor()
#1.获取链接对象的方法
def getConn(self):
return self.conn

# 2.获取游标对象的方法
def getCursor(self):
    return self.cursor

# 3.处理一个数据
def getOnedata(self,sql,param=None):
    cursor  =self.conn.cursor()
    cursor.execute(sql,param)
    #获取一个数据
    one= cursor.fetchone()
    cursor.close()
    return one[0]

def getManydata(self,sql, param=None):
    cursor = self.conn.cursor()
    cursor.execute(sql,param)
    # 获取多个数据
    row = cursor.fetchall()
    cursor.close()
    return row

# 4.处理非查询的处理方法
def unquery(self,sql,args=None):
    cursor =self.conn.cursor()
    try:
        cursor.execute(sql,args)
        self.conn.commit()
    except Exception as e:
        print(e)
        self.conn.rollback()
    finally:
        self.closeAll()
# 5.关闭资源的方法
def closeAll(self):
    self.cursor.close()
    self.conn.close()

“”"
插入语句
untils = pymysql_class()
sql = “insert into stu(id,sname,saddress) values(%s,%s,%s)”
args = (5,‘xusdb’,‘xnaud’)
untils.unquery(sql,args )
“”"
“”"
#修改语句
untils = pymysql_class()
sql = “update stu set sname = %s where id = %s "
args = (“xiaoming”,3)
untils.unquery(sql,args )
“””

#删除语句
untils = pymysql_class()
sql = “delete from stu where id = %s”
args = (3)
untils.unquery(sql,args )

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值