import MySQLdb

class MyExcept(Exception):    '''    常见做法定义异常基类,然后在派生不同类型的异常    '''

    def __init__(self, *args):        self.args = args

class DropDataaseError(MyExcept):    def __init__(self):        self.args = ('删除数据库错误!',)        self.message = '删除数据库错误!'        self.code = 100

class DropTableError(MyExcept):    def __init__(self):        self.args = ('删除表错误!',)        self.message = '删除表错误!'        self.code = 200

class CreateDatabaseError(MyExcept):    def __init__(self):        self.args = ('不能创建数据库',)        self.message = '不能创建数据库'        self.code = 300

class OperatorError(MyExcept):    '''    操作错误,一般是要做的事情和实际功能不匹配    '''

    def __init__(self, message):        self.args = (message,)        self.message = message        self.code = 400

class FileIsExistsError(MyExcept):    def __init__(self, message):        self.args = (message,)        self.message = message        self.code = 500

##raise OperatorError('错误消息') # 这里突然返现 raise引发的异常将中断程序import jsonimport os

class Mysql:    conn = None    host = None    port = None    user = None    passwd = None    charset = None    mysql_name = None    cursor = None

    @classmethod    def create_database(cls, sql):        if 'create database' not in sql:            raise OperatorError('这是创建数据库')        cls.query(sql)        cls.use_database()

    @classmethod    def use_database(cls):        if cls.mysql_name != None:            cls.query('use %s ;' % cls.mysql_name)        else:            raise OperatorError('切换数据库失败')

    @classmethod    def config(cls, mode=False,               host='localhost',               port=3306,               mysql_name='test',               user='root',               passwd='',               charset='utf8',               path='config.json'):        '''        连接数据库配置文件        :param mode: mode false 默认为自动传值,true 为从json配置文件里面获取数据        :param host:ip 默认为空localhost        :param port: 端口 默认为3306        :param mysql_name: 数据库名称 必须指定        :param user: 用户名称,默认值为root        :param passwd: 默认密码为空        :param charset: 默认字符编码为utf8        :param cursorclass:Faslse 不指定MySQLdb.cursors.DictCursor,True指定为MySQLdb.cursors.DictCursor        :return: NUll        '''

        if not mode:

            if {'', ' ', '  ', None} & {host, port, user, charset, mysql_name}:                raise OperatorError(                    "host,port,user,charset可以不传值,但是不能传空值!,也不可为空格")

            Mysql.host = host            Mysql.port = port            Mysql.user = user            Mysql.passwd = passwd            Mysql.charset = charset            Mysql.mysql_name = mysql_name

        if mode:            if not os.path.exists(path):                raise FileIsExistsError('文件不存在')

            with open(path, 'rt', encoding='utf8') as f:                config_json_dic = json.load(f)

            Mysql.host = config_json_dic['host']            Mysql.port = config_json_dic['port']            Mysql.user = config_json_dic['user']            Mysql.passwd = config_json_dic['passwd']            Mysql.charset = config_json_dic['charset']

        try:            Mysql.conn = MySQLdb.connect(host=Mysql.host,                                         port=Mysql.port,                                         user=Mysql.user,                                         passwd=Mysql.passwd,                                         db=Mysql.mysql_name,                                         charset=Mysql.charset)        except Exception as e:            Mysql.conn.close()            print(e)        else:            Mysql.get_cursor()            # cls.use_database()

    @classmethod    def get_cursor(cls, mode=False):  # --------------------------        '''        获取操作的游标        :return: Null        '''        if not mode:            Mysql.cursor = Mysql.conn.cursor()        else:            Mysql.cursor = Mysql.conn.cursor(                cursorclass=MySQLdb.cursors.DictCursor)

    @classmethod    def having_sql(cls, sql):        '''        sql 过滤        :param sql:需要过滤的sql        :return:过滤后的sql        '''        # 没有写好        return True

    @classmethod    def query(cls, sql):        '''        底层 sql 执行语句        :param sql: sql语句        :return:        '''        # if 'drop table' in sql:        #     raise ValueError('不允许删除表!')        #        # if 'drop database' in sql:        #     raise ValueError('不允许删除数据库')

        if {'', ' ', '  ', None} & {Mysql.host, Mysql.port, Mysql.user,                                    Mysql.charset, Mysql.mysql_name}:            raise ValueError("host,port,user,charset可以不传值,但是不能传空值!")

        if not cls.having_sql(sql):            raise ValueError('含有非法字符')

        try:            Mysql.cursor.execute(sql)            Mysql.conn.commit()  # 提交        except:            Mysql.conn.rollback()  # 回滚操作            return False        else:            return True

    @classmethod    def update(cls, sql):        if not ('update' in sql):            raise OperatorError('更新表记录!')

        return Mysql.query(sql)

    @classmethod    def truncate(cls, sql):        if not ('truncate' in sql):            raise OperatorError('清空表记录操作')

        return Mysql.query(sql)

    @classmethod    def delete(cls, sql):        if not ('delete' in sql):            raise OperatorError('删除表记录!')

        return Mysql.query(sql)

    @classmethod    def create(cls, sql):        if not ('create table' in sql):            raise OperatorError('创建表!')

        if 'create database' in sql:            raise CreateDatabaseError()

        return Mysql.query(sql)

    @classmethod    def insert(cls, sql):        if not ('insert into' in sql):            raise OperatorError('插入记录!')

        return Mysql.query(sql)

    @classmethod    def insert_many(cls, sql, res):        '''        批量插入        :param sql:sql sample:insert into talbe_name values(0,%s,%s,%s,%s,%s)        :param res:res sample:((title,singer,imgurl,url,alpha),(title2,singer2,imgurl2,url2,alpha2))        :return line: why?        '''        if not ('insert into' in sql):            raise OperatorError('操作错误,这是插入')        if not len(res) or len(res) < 5:            raise ValueError('插入的值不能为空')

        line = Mysql.cursor.executemany(sql, res)        return line

    @classmethod    def get_line(cls, sql):        '''        获取单行的数据        :return:        '''        if not ('select' in sql):            raise OperatorError('执行查询')

        cls.query(sql)

        try:            return True, Mysql.cursor.fetchone();        except:            return False, '没有数据'

    @classmethod    def get_lines(cls, sql):        '''        返回多行数据        :return:        '''        if not ('select' in sql):            raise OperatorError('执行查询')

        cls.query(sql)

        try:            return True, Mysql.cursor.fetchall();        except Exception as e:            print(e)            return False, '没有数据'

    @classmethod    def get_fetchmany(cls, sql, size=1):        '''        获取指定数量数据        :param size: 接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数        :return:tuple        '''        if not isinstance(size, int):            raise TypeError('类型错误')

        if size <= 0:            return None;

        if not ('select' in sql):            raise OperatorError('执行查询')

        cls.query(sql)

        return Mysql.cursor.fechmany(size)

    @classmethod    def close(cls):        '''        关闭cursor 和db 连接        :return:        '''        Mysql.cursor.close()        Mysql.conn.close()

    #    # @classmethod    # def __del__():    #     Mysql.close()

自定义 Mysql 类 与 自定义 异常类的更多相关文章

  1. 【转】【C#】异常类 Exception 枚举所有类型的异常

    一.基础 在C# 里,异常处理就是C# 为处理错误情况提供的一种机制.它为每种错误情况提供了定制的处理方式,并且把标识错误的代码与处理错误的代码分离开来. 对.NET类来说,一般的 异常类System ...

  2. Java学习(异常类)

    一.什么是异常: 异常就是在运行时产生的问题.通常用Exception描述. 在java中,把异常封装成了一个类,当出现问题时,就会创建异常类对象并抛出异常相关的信息(如详细信息,名称以及异常所处的位 ...

  3. Java异常类及处理

    异常概述:运行时发生的不正常情况 在java中用类的形式对不正常的情况进行了描述和封装对象. 描述不正常的类,称之为异常类. 异常就是java通过面向对象的思想将问题封装成了对象,用异常类对其进行描述 ...

  4. C#异常类相关总结

    C#异常类相关总结 C#异常类相关总结 C#异常类一.基类ExceptionC#异常类二.常见的异常类1.SystemException类:该类是System命名空间中所有其他异常类的基类.(建议:公 ...

  5. C#异常类总结

    http://msdn.microsoft.com/zh-cn/library/aa664610(v=vs.71).aspx C#异常类相关总结 C#异常类一.基类Exception C#异常类二.常 ...

  6. java内部类和异常类的概念

    1.内部类的外嵌类的成员变量在内部类中任然有效,内部类中的方法也可以调用外嵌类中的 方法,内部类中不可以声明类的变量和方法,外嵌的类体可以用内部类声明对象,作为外嵌类的成员.内部类仅供他的外嵌类使用. ...

  7. java异常,异常处理,异常类 关键字:throws 和 throw 自定义的异常类

    package cn.kecheng; import java.util.Scanner; /**异常:异常是指在程序的运行过程中所发生的不正常的情况,它会中断正在运行的程序 异常处理机制:java中 ...

  8. 自定义Springboot全局异常类

    一.简要说明 如何实现网上文章基本是随便一搜就可以很快找到, 这里不再赘述. 二.Spring-web和Spring-webmvc 通过idea查看到两个注解位于 spring-web-5.2.2.R ...

  9. java中自定义一个异常类 在某些情况抛出自定的异常 ----------阻断程序

    //=============定义异常类 package org.springblade.flow.engine.errorException; /** * 自定义异常处理写入sap失败 */ pub ...

  10. PHP (Yii2) 自定义业务异常类(可支持返回任意自己想要的类型数据)

    public function beforeAction($action) { return parent::beforeAction($action); } public function runA ...

随机推荐

  1. Python读取图片尺寸、图片格式

    Python读取图片尺寸.图片格式 需要用到PIL模块,使用pip安装Pillow.Pillow是从PIL fork过来的Python 图片库. from PIL import Image im = ...

  2. C#中让WebBrowser运行Javascript脚本

    C#中可以让Webbrowser运行Javascript脚本来实现各种自动化操作,比如点击网页上的按钮,输入用户名密码等等.代码也很简单: >>>>>>>&g ...

  3. 升级tensorflow1.0到1.3,报错ImportError: libcudnn.so.6: cannot open shared object file: No such file or directory Failed to load the native TensorFlow runtime.

    先定位问题,发现在 /usr/local/cuda/include/ /usr/local/cuda/lib64/ 下面只有 libcudnn.so.5 因此,只要下载cudnn6.*版本的文件分别覆 ...

  4. tensorflow serving 中 No module named tensorflow_serving.apis,找不到predict_pb2问题

    最近在学习tensorflow serving,但是运行官网例子,不使用bazel时,发现运行mnist_client.py的时候出错, 在api文件中也没找到predict_pb2,因此,后面在网上 ...

  5. lcd 控制器

    1. 使用lcd 一般需要一个控制器和驱动器,控制器需要初始化以产生正确的时序,驱动器一般是和lcd基板制作在一起. LCD 控制器结构图: REGBANK 表示调色板 LCDDMA 表示DMA通道 ...

  6. SAP 自定义进度条

    *&---------------------------------------------------------------------* *& Report ZCHENH028 ...

  7. java fastJson

    // 大区的数据 String cityList = "[{'title':'华北','value':'1','children':[{'title':'山东','value':'1.1', ...

  8. 递归算法结合数据库 解析 java树形结构

    1.准备表结构及对应的表数据a.表结构: create table TB_TREE ( CID NUMBER not null, CNAME VARCHAR2(50), PID NUMBER //父节 ...

  9. Parallax Mapping

    [Parallax Mapping] Parallax mapping belongs to the family of displacement mapping techniques that di ...

  10. mysql 模糊搜索

    [mysql 模糊搜索] like,%,_,[],[^] 参考:http://www.jb51.net/article/31904.htm