码迷,mamicode.com
首页 > 数据库 > 详细

python pyMysql 自定义异常 函数重载

时间:2018-07-25 01:02:35      阅读:362      评论:0      收藏:0      [点我收藏+]

标签:ali   ref   %s   hang   可变   接收   tin   obj   fetchall   

# encoding=‘utf8‘
# auth:yanxiatingyu
#2018.7.24

import pymysql

__all__ = [‘Mymysql‘]


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


class Mymysql:
host = None
port = None
user = None
passpwd = None
database = None
charset = None

conn = None
cursor = None

@classmethod
def config(cls, db, host=‘localhost‘, port=3306, user=‘root‘, pwd=‘‘,
charset=‘utf8‘):
cls.host = host
cls.port = port
cls.user = user
cls.passpwd = pwd
cls.database = db
cls.charset = charset
cls.__init_connect()
cls.__new_course()

@classmethod
def __init_connect(cls):
cls.conn = pymysql.connect(
host=cls.host,
port=cls.port,
user=cls.user,
password=cls.passpwd,
database=cls.database,
charset=cls.charset
)

@classmethod
def __new_course(cls):
cls.cursor = cls.conn.cursor()

## userinfo=[
# (3,"alex"),
# (4,"lxx"),
# (5,"yxx")
#
# sql=‘insert into student values(%s,%s,%s);‘
# cursor.executemany(sql,userinfo)
@classmethod
def filter(cls, sql):
‘‘‘
过滤sql语句
:param sql:
:return: 返回过滤后的sql语句
‘‘‘

return sql.lower()

# @multimethod
# def __query(cls, sql):
# msg = 0
# try:
# msg = cls.cursor.execute(cls.filter(sql))
# cls.conn.commit()
# except Exception as e:
# cls.conn.rollback()
# finally:
# return msg

@classmethod
def __query(cls, sql,*args):
‘‘‘
底层查询
:param sql:
:param args:
:return: rows 操作成功返回受影响的行数
‘‘‘
rows = 0
try:
rows = cls.cursor.execute(cls.filter(sql), *args)
cls.conn.commit()
except Exception as e:
cls.conn.rollback()
finally:
return rows

@classmethod
def insert(cls, sql, args):
if not (‘insert into‘ in sql.lower()):
raise OperatorError(‘这是插入操作!‘)
return cls.__query(sql, args)

@classmethod
def update(cls, sql): # update test set name=‘你好‘ where name=‘egon‘;
if not (‘update‘ in sql.lower()):
raise OperatorError(‘这是更新操作‘)
return cls.__query(sql)

@classmethod
def drop(cls, sql):

if not (‘drop‘ in sql.lower()): # drop table test;
raise OperatorError(‘无法提供非drop table类的方法‘)

if not (‘drop database‘ in sql):
raise OperatorError(‘无法删除数据库!‘)

return cls.__query(sql)

@classmethod
def delete(cls, sql):
if not (‘delete ‘ in sql.lower()):
raise OperatorError(‘无法提供非delete 记录操作!‘)
return cls.__query(sql)

# 记录级别
# alter table test add age int;
# alter table test modify name char(15);
# alter table test change NAME char(15);#
# alter table test drop age;
@classmethod
def alter(cls, sql):
if not (‘alter‘ in sql.lower()):
raise OperatorError(‘只能提供修改操作‘)

if not (‘alter database‘ in sql):
raise OperatorError(‘操作错误你大爷‘)

return cls.__query(cls)

@classmethod
def create(cls, sql):
if not (‘create database‘ in sql.lower()):
raise OperatorError(‘不准创库操作‘)

if not (‘create table‘ in sql):
raise OperatorError(‘操作错误‘)

return cls.__query(sql)

@classmethod
def truncate(cls, table_name):
table_name = table_name.strip()
if not isinstance(table_name, str):
raise TypeError(‘类型错误‘)
return cls.__query(‘truncate %s;‘ % table_name)

# update test set name=‘lxx_dsb‘ where id=2;
# update yanxiatingyu set name=‘lxx_dsb‘ where name=‘lxx‘;
@classmethod
def update(cls, sql):
if not (‘update‘ in sql):
raise TypeError(‘只能更新‘)
return cls.__query(sql)

@classmethod
def select(cls, sql):
if not (‘select‘ in sql.lower()):
raise OperatorError(‘操作错误‘)
return cls.__query(sql)

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

cls.__query(sql)

try:
return True, cls.cursor.fetchone()
except:
return False, ‘没有数据‘

@classmethod
def get_lines(cls, sql):
‘‘‘
返回多行数据
:return:
‘‘‘
sql = sql.lower()

if not (‘select‘ in sql):
raise OperatorError(‘执行查询‘)
# print(sql.lower())
cls.__query(sql)
try:
return True, cls.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

sql = sql.lower()
if not (‘select‘ in sql):
raise OperatorError(‘执行查询‘)

cls.__query(sql)

return cls.cursor.fechmany(size)

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


Mymysql.config(db=‘db1‘)
res = Mymysql.get_lines(‘select * from student;‘)
print(res)


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

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

cls.host = config_json_dic[‘host‘]
cls.port = config_json_dic[‘port‘]
cls.user = config_json_dic[‘user‘]
cls.passwd = config_json_dic[‘passwd‘]
cls.charset = config_json_dic[‘charset‘]


 

函数重载主要是为了解决两个问题。

  1. 可变参数类型。
  2. 可变参数个数。

另外,一个基本的设计原则是,仅仅当两个函数除了参数类型和参数个数不同以外,其功能是完全相同的,此时才使用函数重载,如果两个函数的功能其实不同,那么不应当使用重载,而应当使用一个名字不同的函数。

好吧,那么对于情况 1 ,函数功能相同,但是参数类型不同,python 如何处理?答案是根本不需要处理,因为 python 可以接受任何类型的参数,如果函数的功能相同,那么不同的参数类型在 python 中很可能是相同的代码,没有必要做成两个不同函数。

那么对于情况 2 ,函数功能相同,但参数个数不同,python 如何处理?大家知道,答案就是缺省参数。对那些缺少的参数设定为缺省参数即可解决问题。因为你假设函数功能相同,那么那些缺少的参数终归是需要用的。

好了,鉴于情况 1 跟 情况 2 都有了解决方案,python 自然就不需要函数重载了。

 

I‘m learning Python (3.x) from a Java background.

I have a python program where I create a personObject and add it to a list.

p = Person("John")
list.addPerson(p)

But for flexibility I also want to be able to declare it directly in the addPerson method, like so:

list.addPerson("John")

The addPerson method will be able to differentiate whether or not I‘m sending a Person-object or a String.

In Java I would create two separate methods, like this:

void addPerson(Person p) {
    //Add person to list
}

void addPerson(String personName) {
    //Create Person object
    //Add person to list
}

I‘m not able to find out how to do this in Python. I know of a type() function, which I could use to check whether or not the parameter is a String or an Object. However, that seems messy to me. Is there another way of doing it?

EDIT:

I guess the alternative workaround would be something like this(python):

def addPerson(self, person):
    //check if person is string
        //Create person object

    //Check that person is a Person instance
        //Do nothing

    //Add person to list

But it seems messy compared to the overloading solution in Java.

解决方案

Using the reference pointed by @Kevin you can do something like:

from multimethod import multimethod

class Person(object):
    def __init__(self, myname):
        self.name = myname

    def __str__(self):
        return self.name

    def __repr__(self):
        return self.__str__()


@multimethod(list, object)
def addPerson(l, p):
    l = l +[p]
    return l

@multimethod(list, str)
def addPerson(l, name):
    p = Person(name)
    l = l +[p]
    return l


alist = []
alist = addPerson(alist, Person("foo"))
alist = addPerson(alist, "bar")
print(alist)

The result will be:

$ python test.py
[foo, bar]

(you need to install multimethod first)

 

 

http://www.it1352.com/779685.html

python pyMysql 自定义异常 函数重载

标签:ali   ref   %s   hang   可变   接收   tin   obj   fetchall   

原文地址:https://www.cnblogs.com/yanxiatingyu/p/9363320.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!