• 好用封装好的函数


    (1)数据库类
    import pymysql
    class MyCoonect(object):
    def __init__(self, host, port, user, passwd, db, charset='utf8'):
    self.__host = host
    self.port = port
    self.user = user
    self.passwd = passwd
    self.db = db
    self.charset = charset
    self.__get_cur() # 在类初始化的时候就去调用创建游标的函数

    def __get_cur(self):
    try:
    self.coon = pymysql.connect(
    host=self.__host, port=self.port, user=self.user, passwd=self.passwd,
    charset=self.charset, db=self.db
    )
    except Exception as e:
    print('这里出错了,错误信息是【%s】'%e)
    else:
    self.cur = self.coon.cursor() # 建立游标

    def select_sql(self, sql):
    self.cur.execute(sql)
    return self.cur.fetchall()

    def other_sql(self, sql):
    try:
    self.cur.execute(sql)
    except Exception as e:
    print('sql执行失败%s' % e)
    else:
    self.coon.commit()

    def __del__(self):
    self.cur.close()
    self.coon.close()
    # 在类里面,如果你想用self.xx,那么你必须先赋值 self.name = 'xxxx'
    (2)def con_sql(sql):#连接数据库,如果是查询语句,返回结果;如果是改,查就提交
    con = pymysql.connect(host = MYSQL_HOST,port=MYSQL_PORT,db=DB,user =USER,password=PASSWORD,charset='utf8')
    cur =con.cursor()
    cur.execute(sql)
    res =cur.fetchall()
    con.commit()
    cur.close()
    con.close()
    return res

    (3)def md5(str):#加密
    md =hashlib.md5()
    md.update(str.encode())
    return md.hexdigest()

    (4)把字符串转换成字典
    aa='n=jmy&p=123'
    def dic(strr):
    d={}
    for i in string.punctuation:
    if i in strr:
    strr =strr.replace(i,',')
    l = strr.split(',')
    for o,k in zip(l[::2],l[1::2]):
    d.setdefault(o,k)
    return d
  • 相关阅读:
    人月神话 另外一面
    python论文爬取(五)
    Python词云
    python安装wordcloud库出错及其解决办法(使用命令行安装)
    人月神话 祸起萧墙
    python论文爬取(四)
    个人课程总结
    python论文爬取(三)
    python论文爬取(一)
    win10子系统ubuntu开机启动ssh服务
  • 原文地址:https://www.cnblogs.com/lanxia/p/7908700.html
Copyright © 2020-2023  润新知