python与数据库的操作封装

简单了封装了几个接口,剩下的接口可以自行添加,格式是一样的

import MySQLdb

class MysqlDemo(object):
    def __init__(self,prot,host,user,passwd,charset):
        self.prot = prot
        self.host = host
        self.user = user
        self.passwd = passwd
        self.charset = charset

    def open(self):
        """打开数据库"""
        self.coon = MySQLdb.connect(host=self.host,prot=self.prot,user=self.user,passwd=self.passwd)
        self.cursor = self.coon.cursor()

    def close(self):
        """关闭数据库连接"""
        self.cursor.close()
        self.coon.close()

    def insertSQL(self,SQL,promat=[]):
        """插入数据库"""
        try:
            self.open()
            self.cursor.execute(SQL,promat)
            self.coon.commit()
            self.close()
        except Exception as e:
            print(e)

    def readSQL(self,SQL,promat=[]):
        """读取数据库"""
        try:
            self.open()
            self.cursor.execute(SQL, promat)
            result = self.cursor.fetchall()
            self.close()
            return result
        except Exception as e:
            print(e)

简单的数据库链接框架 其他操作方法按照这个格式添加

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容