• Python3数据库封装


    # coding=utf-8
    __author__ = "leslie"
    import pymysql,pymysql.err
    from CaseApi.common.readConfig import read
    from CaseApi.common.caseLog import Log

    class MysqlDb:
    def __init__(self):
    self.log = Log() # 实例化日志类
    def __db(self):
         '''定义私有方法连接数据库'''
    host = read('mysql','host')
    user = read('mysql','user')
    password = read('mysql','password')
    database = read('mysql','db')
    try:
    self.db = pymysql.connect(host,user,password,database)
    return self.db
    except Exception as e:
    self.log.error ("链接出错: %s"%e)
    # self.__db = pymysql.connect(host, user, password, database)
    # return self.__db

    def select(self,form,table,condition):
    sql = '''select {} from {} {};'''.format(form,table,condition)
    self.log.info(sql)
    cursor = self.__db().cursor()
    try:
    cursor.execute(sql)
    result = cursor.fetchall()
    self.__db().close()
    self.log.debug(result)
    list = []
    for i in result:
    date = {}
    date['user'] = i[0]
    date['psw'] = i[1]
    date['mail'] = i[2]
    list.append(date)
    return list
    except Exception as e:
    self.log.error(e)

    def insert(self,table):
    sql = '''insert into %s;'''%table
    self.log.info(sql)
    cursor = self.__db().cursor()
    try:
    cursor.execute(sql)
    self.__db().commit()
    self.__db().close()
    except Exception as e:
    self.log.error(e)

    def update(self,table,condition):
    sql = '''update {} set {};'''.format(table,condition)
    self.log.info(sql)
    cursor = self.__db().cursor()
    try:
    cursor.execute(sql)
    self.__db().commit()
    self.__db().close()
    except Exception as e:
    self.log.error(e)

    def delete(self,table,condition):
    sql = '''delete from {} {};'''.format(table,condition)
    self.log.info(sql)
    cursor = self.__db().cursor()
    try:
    cursor.execute(sql)
    self.__db().commit()
    self.__db().close()
    except Exception as e:
    self.log.error(e)
  • 相关阅读:
    《C#从现象到本质》读书笔记(八)第10章反射
    《C#从现象到本质》读书笔记(七)第9章 泛型
    《C#从现象到本质》读书笔记(六)第8章委托和事件
    《C#从现象到本质》读书笔记(五)第5章字符串第6章垃圾回收第7章异常与异常处理
    求1+2+……+n的和
    回溯法的应用举例
    回溯法
    翻转单词顺序列
    左旋转字符串
    和为S的两个数字
  • 原文地址:https://www.cnblogs.com/leslie003/p/11399780.html
Copyright © 2020-2023  润新知