python pyMysql 鑷畾涔夊紓甯? 鍑芥暟閲嶈浇

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python pyMysql 鑷畾涔夊紓甯? 鍑芥暟閲嶈浇相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/ali' title='ali'>ali   ref   %s   hang   鍙彉   鎺ユ敹   tin   obj   fetchall   

# encoding=鈥榰tf8鈥?br># auth:yanxiatingyu
#2018.7.24

import pymysql

__all__ = [鈥楳ymysql鈥榏


class MyExcept(Exception):
鈥樷€樷€?br> 甯歌鍋氭硶瀹氫箟寮傚父鍩虹被,鐒跺悗鍦ㄦ淳鐢熶笉鍚岀被鍨嬬殑寮傚父
鈥樷€樷€?br>
def __init__(self, *args):
self.args = args


class DropDataaseError(MyExcept):
def __init__(self):
self.args = (鈥樺垹闄ゆ暟鎹簱閿欒!鈥?)
self.message = 鈥樺垹闄ゆ暟鎹簱閿欒!鈥?br> self.code = 100


class DropTableError(MyExcept):
def __init__(self):
self.args = (鈥樺垹闄よ〃閿欒!鈥?)
self.message = 鈥樺垹闄よ〃閿欒锛佲€?br> self.code = 200


class CreateDatabaseError(MyExcept):
def __init__(self):
self.args = (鈥樹笉鑳藉垱寤烘暟鎹簱鈥?)
self.message = 鈥樹笉鑳藉垱寤烘暟鎹簱鈥?br> self.code = 300


class OperatorError(MyExcept):
鈥樷€樷€?br> 鎿嶄綔閿欒,涓€鑸槸瑕佸仛鐨勪簨鎯呭拰瀹為檯鍔熻兘涓嶅尮閰?br> 鈥樷€樷€?br>
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=鈥榣ocalhost鈥? port=3306, user=鈥榬oot鈥? pwd=鈥樷€?
charset=鈥榰tf8鈥?:
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=鈥榠nsert into student values(%s,%s,%s);鈥?br> # cursor.executemany(sql,userinfo)
@classmethod
def filter(cls, sql):
鈥樷€樷€?br> 杩囨护sql璇彞
:param sql:
:return: 杩斿洖杩囨护鍚庣殑sql璇彞
鈥樷€樷€?br>
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):
鈥樷€樷€?br> 搴曞眰鏌ヨ
:param sql:
:param args:
:return: rows 鎿嶄綔鎴愬姛杩斿洖鍙楀奖鍝嶇殑琛屾暟
鈥樷€樷€?br> 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 (鈥榠nsert into鈥?in sql.lower()):
raise OperatorError(鈥樿繖鏄彃鍏ユ搷浣?鈥?
return cls.__query(sql, args)

@classmethod
def update(cls, sql): # update test set name=鈥樹綘濂解€? where name=鈥榚gon鈥?
if not (鈥榰pdate鈥?in sql.lower()):
raise OperatorError(鈥樿繖鏄洿鏂版搷浣溾€?
return cls.__query(sql)

@classmethod
def drop(cls, sql):

if not (鈥榙rop鈥?in sql.lower()): # drop table test;
raise OperatorError(鈥樻棤娉曟彁渚涢潪drop table绫荤殑鏂规硶鈥?

if not (鈥榙rop database鈥?in sql):
raise OperatorError(鈥樻棤娉曞垹闄ゆ暟鎹簱锛佲€?

return cls.__query(sql)

@classmethod
def delete(cls, sql):
if not (鈥榙elete 鈥?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 (鈥榓lter鈥?in sql.lower()):
raise OperatorError(鈥樺彧鑳芥彁渚涗慨鏀规搷浣溾€?

if not (鈥榓lter database鈥?in sql):
raise OperatorError(鈥樻搷浣滈敊璇綘澶х埛鈥?

return cls.__query(cls)

@classmethod
def create(cls, sql):
if not (鈥榗reate database鈥?in sql.lower()):
raise OperatorError(鈥樹笉鍑嗗垱搴撴搷浣溾€?

if not (鈥榗reate 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(鈥榯runcate %s;鈥?% table_name)

# update test set name=鈥榣xx_dsb鈥?where id=2;
# update yanxiatingyu set name=鈥榣xx_dsb鈥?where name=鈥榣xx鈥?
@classmethod
def update(cls, sql):
if not (鈥榰pdate鈥?in sql):
raise TypeError(鈥樺彧鑳芥洿鏂扳€?
return cls.__query(sql)

@classmethod
def select(cls, sql):
if not (鈥榮elect鈥?in sql.lower()):
raise OperatorError(鈥樻搷浣滈敊璇€?
return cls.__query(sql)

@classmethod
def get_line(cls, sql):
鈥樷€樷€?br> 鑾峰彇鍗曡鐨勬暟鎹?br> :return:
鈥樷€樷€?br> if not (鈥榮elect鈥?in sql):
raise OperatorError(鈥樻墽琛屾煡璇⑩€?

cls.__query(sql)

try:
return True, cls.cursor.fetchone()
except:
return False, 鈥樻病鏈夋暟鎹€?br>
@classmethod
def get_lines(cls, sql):
鈥樷€樷€?br> 杩斿洖澶氳鏁版嵁
:return:
鈥樷€樷€?br> sql = sql.lower()

if not (鈥榮elect鈥?in sql):
raise OperatorError(鈥樻墽琛屾煡璇⑩€?
# print(sql.lower())
cls.__query(sql)
try:
return True, cls.cursor.fetchall()
except Exception as e:
print(e)
return False, 鈥樻病鏈夋暟鎹€?br>
@classmethod
def get_fetchmany(cls, sql, size=1):
鈥樷€樷€?br> 鑾峰彇鎸囧畾鏁伴噺鏁版嵁
:param size: 鎺ユ敹size鏉¤繑鍥炵粨鏋滆.濡傛灉size鐨勫€煎ぇ浜庤繑鍥炵殑缁撴灉琛岀殑鏁伴噺,鍒欎細杩斿洖cursor.arraysize鏉℃暟
:return:tuple
鈥樷€樷€?br> if not isinstance(size, int):
raise TypeError(鈥樼被鍨嬮敊璇€?

if size <= 0:
return None

sql = sql.lower()
if not (鈥榮elect鈥?in sql):
raise OperatorError(鈥樻墽琛屾煡璇⑩€?

cls.__query(sql)

return cls.cursor.fechmany(size)

@classmethod
def close(cls):
鈥樷€樷€?br> 鍏抽棴cursor 鍜宒b 杩炴帴
:return:
鈥樷€樷€?br> cls.cursor.close()
cls.conn.close()


Mymysql.config(db=鈥榙b1鈥?
res = Mymysql.get_lines(鈥榮elect * from student;鈥?
print(res)


#config
if mode:
if not os.path.exists(path):
raise FileIsExistsError(鈥樻枃浠朵笉瀛樺湪鈥?

with open(path, 鈥榬t鈥? encoding=鈥榰tf8鈥? as f:
config_json_dic = json.load(f)

cls.host = config_json_dic[鈥榟ost鈥榏
cls.port = config_json_dic[鈥榩ort鈥榏
cls.user = config_json_dic[鈥榰ser鈥榏
cls.passwd = config_json_dic[鈥榩asswd鈥榏
cls.charset = config_json_dic[鈥榗harset鈥榏


 

鍑芥暟閲嶈浇涓昏鏄负浜嗚В鍐充袱涓棶棰樸€?/p>

  1. 鍙彉鍙傛暟绫诲瀷銆?/li>
  2. 鍙彉鍙傛暟涓暟銆?/li>

鍙﹀锛屼竴涓熀鏈殑璁捐鍘熷垯鏄紝浠呬粎褰撲袱涓嚱鏁伴櫎浜嗗弬鏁扮被鍨嬪拰鍙傛暟涓暟涓嶅悓浠ュ锛屽叾鍔熻兘鏄畬鍏ㄧ浉鍚岀殑锛屾鏃舵墠浣跨敤鍑芥暟閲嶈浇锛屽鏋滀袱涓嚱鏁扮殑鍔熻兘鍏跺疄涓嶅悓锛岄偅涔堜笉搴斿綋浣跨敤閲嶈浇锛岃€屽簲褰撲娇鐢ㄤ竴涓悕瀛椾笉鍚岀殑鍑芥暟銆?/p>

濂藉惂锛岄偅涔堝浜庢儏鍐?1 锛屽嚱鏁板姛鑳界浉鍚岋紝浣嗘槸鍙傛暟绫诲瀷涓嶅悓锛宲ython 濡備綍澶勭悊锛熺瓟妗堟槸鏍规湰涓嶉渶瑕佸鐞嗭紝鍥犱负 python 鍙互鎺ュ彈浠讳綍绫诲瀷鐨勫弬鏁帮紝濡傛灉鍑芥暟鐨勫姛鑳界浉鍚岋紝閭d箞涓嶅悓鐨勫弬鏁扮被鍨嬪湪 python 涓緢鍙兘鏄浉鍚岀殑浠g爜锛屾病鏈夊繀瑕佸仛鎴愪袱涓笉鍚屽嚱鏁般€?/p>

閭d箞瀵逛簬鎯呭喌 2 锛屽嚱鏁板姛鑳界浉鍚岋紝浣嗗弬鏁颁釜鏁颁笉鍚岋紝python 濡備綍澶勭悊锛熷ぇ瀹剁煡閬擄紝绛旀灏辨槸缂虹渷鍙傛暟銆傚閭d簺缂哄皯鐨勫弬鏁拌瀹氫负缂虹渷鍙傛暟鍗冲彲瑙e喅闂銆傚洜涓轰綘鍋囪鍑芥暟鍔熻兘鐩稿悓锛岄偅涔堥偅浜涚己灏戠殑鍙傛暟缁堝綊鏄渶瑕佺敤鐨勩€?/p>

濂戒簡锛岄壌浜庢儏鍐?1 璺?鎯呭喌 2 閮芥湁浜嗚В鍐虫柟妗堬紝python 鑷劧灏变笉闇€瑕佸嚱鏁伴噸杞戒簡銆?/p>

 

I鈥榤 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鈥榤 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鈥榤 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.

瑙e喅鏂规

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 鑷畾涔夊紓甯? 鍑芥暟閲嶈浇的主要内容,如果未能解决你的问题,请参考以下文章

绫诲畾涔夊拰瀵硅薄鍒涘缓

鑷畾涔夌殑鍒嗛〉

flask鑷畾涔夎浆鎹㈠櫒

Django API 鑷畾涔夌姸鎬佺爜

浣跨敤 FiddlerCore 鑷畾涔?HTTP/HTTPS 缃戠粶浠g悊

Android 鑷畾涔塋istView鍗曞嚮浜嬩欢澶辨晥