zoukankan      html  css  js  c++  java
  • python之MySQL学习——简单的增删改查封装

    1.增删改查封装类MysqlHelper.py

     1 import pymysql as ps
     2 
     3 class MysqlHelper:
     4     def __init__(self, host, user, password, database, charset):
     5         self.host = host
     6         self.user = user
     7         self.password = password
     8         self.database = database
     9         self.charset = charset
    10         self.db = None
    11         self.curs = None
    12     # 数据库连接
    13     def open(self):
    14         self.db = ps.connect(host=self.host, user=self.user, password=self.password,database=self.database, charset=self.charset)
    15         self.curs = self.db.cursor()
    16     # 数据库关闭
    17     def close(self):
    18         self.curs.close()
    19         self.db.close()
    20     # 数据增删改
    21     def cud(self, sql, params):
    22         self.open()
    23         try:
    24             self.curs.execute(sql, params)
    25             self.db.commit()
    26             print("ok")
    27         except :
    28             print('cud出现错误')
    29             self.db.rollback()
    30         self.close()
    31     # 数据查询
    32     def find(self, sql, params):
    33         self.open()
    34         try:
    35             result = self.curs.execute(sql, params)
    36             self.close()
    37             print("ok")
    38             return result
    39         except:
    40             print('find出现错误')

    2.数据查询(引入封装类)

    1 from MysqlHelper import MysqlHelper
    2 
    3 mh = MysqlHelper('localhost', 'root', '123456', 'test', 'utf8')
    4 sql = "select * from user where name=%s"
    5 print(mh.find(sql, '小明'))

    3.数据修改(引入封装类)

    1 from MysqlHelper import MysqlHelper
    2 
    3 mh = MysqlHelper('localhost', 'root', '123456', 'test', 'utf8')
    4 sql = "insert into user(name,password) values(%s,%s)"
    5 mh.cud(sql, ('小光', '123456'))
  • 相关阅读:
    Python随笔之字典Dict
    Python随笔之列表List
    Python基础整理,懒得分类了,大家对付看看吧
    shell批量推送公钥脚本
    Xcode 切换target 之后打包失败
    百度导航sdk错误日志
    前端项目中去掉替换双引号
    taro3.x项目中引用taro-ui以及taro-iconfont-cli
    taro
    JS中some() every() forEach() map() filter()的区别
  • 原文地址:https://www.cnblogs.com/xiaomingzaixian/p/7126869.html
Copyright © 2011-2022 走看看