数据库(三)python简单Mysql的crud

import MySQLdb

class Model(object):

    def __init__(self,host='127.0.0.1',username="root",password="123456",db="test"):
        """
        :param host:主机IP
        :type host :str
        :param username:账号
        :type username:str
        :param password:密码
        :type password:str
        :param db:数据库名
        :type db:str
        """
        self.db = MySQLdb.connect(host,username,password,db,charset="utf8")
        self.cursor = self.db.cursor()

    def execute(self,sql):
        """
        :param sql:sql语句
        :type sql:str
        """
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except:
            self.db.rollback()

    def addData(self,column,data,table):
        """
        :param column:字段
        :type column:list
        :param data:向字段添加的数据
        :type data:list
        :param table:数据库表
        :type table:str
        """
        columnstr = ",".join(column)
        datastr = "','".join(data)
        sql = "insert into " + table + " ("+ columnstr +") values ('" + datastr +"');"
        self.execute(sql)

    def deleteData(self,where,table):
        """
        :param where:删除条件
        :type where:str
        :param table:删除的表
        :type table:str
        """
        sql = "delete from " + table + " where " + where + ";"
        self.execute(sql)


    def updateData(self,setstr,where,table):
        """
        :param setstr:更新的内容
        :type setstr:str
        :param where:更新的位置
        :type where:str
        :param table:更新的表
        :type table:str
        """
        sql = "update " + table +" set "+ setstr + " where " + where + ";"
        self.execute(sql)

    def selectData(self,table):
        """
        :param table:表名
        :type table:str
        """
        sql = "select * from " + table +";"
        self.cursor.execute(sql)
        return self.cursor.fetchall()

    def __del__(self):
        self.db.close()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值