封装(python 版)

封装

  • 观察前面的文件发现,除了SQL语句及参数不同,其它语句都是一样的
  • 创建MysqlHelper.py文件,定义类
    #encoding=utf8
    import MySQLdb
    
    class MysqlHelper():
        def __init__(self,host,port,db,user,passwd,charset='utf8'):
            self.host=host
            self.port=port
            self.db=db
            self.user=user
            self.passwd=passwd
            self.charset=charset
    
        def connect(self):
            self.conn=MySQLdb.connect(host=self.host,port=self.port,db=self.db,user=self.user,passwd=self.passwd,charset=self.charset)
            self.cursor=self.conn.cursor()
    
        def close(self):
            self.cursor.close()
            self.conn.close()
    
        def get_one(self,sql,params=()):
            result=None
            try:
                self.connect()
                self.cursor.execute(sql, params)
                result = self.cursor.fetchone()
                self.close()
            except Exception, e:
                print e.message
            return result
    
        def get_all(self,sql,params=()):
            list=()
            try:
                self.connect()
                self.cursor.execute(sql,params)
                list=self.cursor.fetchall()
                self.close()
            except Exception,e:
                print e.message
            return list
    
        def insert(self,sql,params=()):
            return self.__edit(sql,params)
    
        def update(self, sql, params=()):
            return self.__edit(sql, params)
    
        def delete(self, sql, params=()):
            return self.__edit(sql, params)
    
        def __edit(self,sql,params):
            count=0
            try:
                self.connect()
                count=self.cursor.execute(sql,params)
                self.conn.commit()
                self.close()
            except Exception,e:
                print e.message
            return count
    添加
    • 创建testInsertWrap.py文件,使用封装好的帮助类完成插入操作
    #encoding=utf8
    from MysqlHelper import *
    
    sql='insert into students(sname,gender) values(%s,%s)'
    sname=raw_input("请输入用户名:")
    gender=raw_input("请输入性别,1为男,0为女")
    params=[sname,bool(gender)]
    
    mysqlHelper=MysqlHelper('localhost',3306,'test1','root','mysql')
    count=mysqlHelper.insert(sql,params)
    if count==1:
        print 'ok'
    else:
        print 'error'
    
    查询一个
    • 创建testGetOneWrap.py文件,使用封装好的帮助类完成查询最新一行数据操作
    #encoding=utf8
    from MysqlHelper import *
    
    sql='select sname,gender from students order by id desc'
    
    helper=MysqlHelper('localhost',3306,'test1','root','mysql')
    one=helper.get_one(sql)
    print one



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C-haidragon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值