Python Pymysql custom exception function overloading

Source: Internet
Author: User
Tags define exception rollback

# encoding= ' UTF8 '
# Auth:yanxiatingyu
#2018.7.24

Import Pymysql

__all__ = [' Mymysql ']


Class Myexcept (Exception):
‘‘‘
Common practices define exception base classes, and then derive different types of exceptions
‘‘‘

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


Class Dropdataaseerror (myexcept):
def __init__ (self):
Self.args = (' Delete database error! ')
self.message = ' Delete database error! '
Self.code = 100


Class Droptableerror (myexcept):
def __init__ (self):
Self.args = (' Delete table error! ')
self.message = ' Delete Table Error! ‘
Self.code = 200


Class Createdatabaseerror (myexcept):
def __init__ (self):
Self.args = (' Cannot create database ',)
Self.message = ' Cannot create database '
Self.code = 300


Class Operatorerror (myexcept):
‘‘‘
Operation error, General is to do things and actual function mismatch
‘‘‘

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):
‘‘‘
Filtering SQL statements
:p Aram sql:
: return: Returns the filtered SQL statement
‘‘‘

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):
‘‘‘
Underlying query
:p Aram sql:
:p Aram args:
: Return:rows operation successfully returns the number of rows affected
‘‘‘
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 to ' in Sql.lower ()):
Raise Operatorerror (' This is an insert operation! ')
return cls.__query (SQL, args)

@classmethod
def update (CLS, SQL): # Update test set name= ' Hello ' where name= ' Egon ';
If not (' Update ' in Sql.lower ()):
Raise Operatorerror (' This is Update operation ')
return cls.__query (SQL)

@classmethod
Def drop (CLS, SQL):

If not (' drop ' in Sql.lower ()): # drop table test;
Raise Operatorerror (' cannot provide a method for a non-drop table class ')

If not (' drop database ' in SQL):
Raise Operatorerror (' Can't delete database! ‘)

return cls.__query (SQL)

@classmethod
def delete (CLS, SQL):
If not (' delete ' in Sql.lower ()):
Raise Operatorerror (' cannot provide non-delete record operation! ‘)
return cls.__query (SQL)

# Record Level
# 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 (' can only provide modification operation ')

If not (' ALTER DATABASE ' in SQL):
Raise Operatorerror (' Operation error your uncle ')

Return Cls.__query (CLS)

@classmethod
DEF create (CLS, SQL):
If not (' Create database ' in Sql.lower ()):
Raise Operatorerror (' no-create library operation ')

If not (' CREATE table ' in SQL):
Raise Operatorerror (' Operation error ')

return cls.__query (SQL)

@classmethod
def truncate (CLS, table_name):
table_name = Table_name.strip ()
If not isinstance (table_name, str):
Raise TypeError (' type error ')
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 (' only update ')
return cls.__query (SQL)

@classmethod
Def select (CLS, SQL):
If not (' select ' in Sql.lower ()):
Raise Operatorerror (' Operation error ')
return cls.__query (SQL)

@classmethod
Def get_line (CLS, SQL):
‘‘‘
Get data for a single row
: return:
‘‘‘
If not (' select ' in sql):
Raise Operatorerror (' Execute query ')

Cls.__query (SQL)

Try
Return True, Cls.cursor.fetchone ()
Except
Return False, ' no data '

@classmethod
Def get_lines (CLS, SQL):
‘‘‘
Return multiple rows of data
: return:
‘‘‘
sql = Sql.lower ()

If not (' select ' in sql):
Raise Operatorerror (' Execute query ')
# Print (Sql.lower ())
Cls.__query (SQL)
Try
Return True, Cls.cursor.fetchall ()
Except Exception as E:
Print (e)
Return False, ' no data '

@classmethod
Def get_fetchmany (CLS, SQL, size=1):
‘‘‘
Gets the specified amount of data
:p Aram Size: Receives a size bar that returns the result row. If the value of size is greater than the number of result rows returned, the number of cursor.arraysize is returned
: Return:tuple
‘‘‘
If not isinstance (size, int):
Raise TypeError (' type error ')

If size <= 0:
Return None

sql = Sql.lower ()
If not (' select ' in sql):
Raise Operatorerror (' Execute query ')

Cls.__query (SQL)

return Cls.cursor.fechmany (size)

@classmethod
def close (CLS):
‘‘‘
Close cursor and DB connections
: 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 (' File not present ')

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 ']


function overloading is mainly to solve two problems.

    1. The variable parameter type.
    2. The number of variable parameters.

In addition, a basic design principle is that only if the function of the two functions is identical except for the parameter type and the number of parameters, then the function overload is used, if the function of two functions is different, then the overload should not be used, but a function with different names should be used.

Okay, so for scenario 1, the functions are the same, but the parameter types are different, how does python handle it? The answer is that there is no need to deal with it, because Python can accept any type of argument, and if the function is the same, then the different parameter types are probably the same code in Python, and there is no need to make two different functions.

So for scenario 2, the function is the same, but the number of parameters is different, how does python handle it? As you know, the answer is the default parameter. Setting the default parameters for those missing parameters solves the problem. Because you assume that functions function the same, then those missing parameters are needed.

Well, given that scenario 1 and Scenario 2 have a solution, Python naturally does not need function overloading.

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)

Flexibility I also want to is able to declare it directly in the Addperson method, like so:

List.addperson ("John")

The Addperson method is able to differentiate whether or not I ' m sending a person-object or a String.

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

void Addperson (person p) {    //add-list}void Addperson (String personname) {    //create Person object    // ADD person to List}

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

EDIT:

I Guess the alternative workaround would is something like this (python):

def addperson (self, person):    //check If the person is        a string//create person object//check This person is    a Perso N instance        //do nothing    //add person to list

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

Solution Solutions

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

From Multimethod import multimethodclass 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 lalist = []alist = Addperson (alist, Person ("foo")) Alist = Addperson (alist, "bar") print (alist)

The result would be:

$ Python test.py[foo, bar]

(You need to install Multimethod first)

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

Python Pymysql custom exception function overloading

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.