• 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'))
  • 相关阅读:
    14.12.5
    Linux文件系统的实现 ZZ
    Linux的inode的理解 ZZ
    下载微软符号表的教程
    Windows内核分析——内核调试机制的实现(NtCreateDebugObject、DbgkpPostFakeProcessCreateMessages、DbgkpPostFakeThreadMessages分析)
    读书笔记|Windows 调试原理学习|持续更新
    UAF漏洞学习
    CVE-2010-3971 CSS内存破坏漏洞分析
    CVE-2012-1876漏洞分析
    CVE-2012-0158个人分析
  • 原文地址:https://www.cnblogs.com/xiaomingzaixian/p/7126869.html
Copyright © 2020-2023  润新知