zoukankan      html  css  js  c++  java
  • python连接mysql与方法的封装

     import pymysql
     
     class Model(object):
         def __init__(self, username='root', password='123456', database='demo', 
                      port=3306, host='localhost'):
             # 创建连接
             self.connection = pymysql.connect(user=username, password=password, database=database,
                                               port=port, host=host, cursorclass=pymysql.cursors.DictCursor)
             # 创建游标
             self.cursor = self.connection.cursor()
     
         # 查询所有数据
         def fetchall(self, sql):
             try:
                 self.__execute(sql)
                 return self.cursor.fetchall()
             except Exception as error:
                 print(error)
     
         # 查询多条数据
         def fetchmany(self, sql, size=1):
             try:
                 self.__execute(sql)
                 return self.cursor.fetchmany(size)
             except Exception as error:
                 print(error)
     
         # 查询一条数据
         def fetchone(self, sql):
             try:
                 self.__execute(sql)
                 return self.cursor.fetchone()
             except Exception as error:
                 print(error)
     
         # 增删改的方法
         def change(self, sql):
             try:
                 self.__execute(sql)
                 self.connection.commit()
             except Exception as error:
                 print(error)
     
         # 执行的私有方法
         def __execute(self, sql):
             self.cursor.execute(sql)
     
         # 关闭连接和游标
         def __del__(self):
             self.connection.close()
             self.cursor.close()
     from data_connect import model
     
     # 实例化Model类
     employee = model.Model()
     res = employee.fetchall('select nickname from employee where job="头领"')[0]
     res1 = employee.fetchmany('select nickname from employee where job="头领"', 2)
     res2 = employee.fetchone('select nickname from employee where name = "宋江"')
     # print(res2)
     
     # 插入一条语句
     employee.change('insert into employee (name)values ("关羽")')
     # 删除一条语句
     employee.change('delete from employee where name="关羽"')
     # 更新一条语句
     # obj.change('update employee set name="张飞"where id=8004')
     
  • 相关阅读:
    Ubuntu 安装 JDK 7 / JDK8 的两种方式
    python 深拷贝 浅拷贝 赋值
    importlib.import_module
    pandas分块读取大量数据集
    win10下安装XGBoost Gpu版本
    win10下安装LGBM GPU版本
    统计自然语言处理(第二版)笔记1
    K-近邻算法
    2019考研的一些心得
    lib和dll的区别与使用
  • 原文地址:https://www.cnblogs.com/Liu928011/p/14773058.html
Copyright © 2011-2022 走看看