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')
     
  • 相关阅读:
    XP下VS2010 数据库实体模型添加代码项使用 ADO.NET DBContext 添加错误
    URL路径优化
    题解poj2096
    对不起
    TELE poj1155 题解
    在 Linux 上创建第一个 Service Fabric Java 应用程序
    关于日常使用Azure MySQL中遇到的连接问题以及排查方法分享
    在 Azure 中创建静态 HTML Web 应用
    修改Linux时区的2种办法
    怎样在 Azure 应用服务中生成和部署 Java API 应用
  • 原文地址:https://www.cnblogs.com/Liu928011/p/14773058.html
Copyright © 2011-2022 走看看