zoukankan      html  css  js  c++  java
  • Python使用笔记27--mysql操作封装类

    1、面向过程

     1 import pymysql
     2 
     3 #面向过程
     4 mysql_info = {'host':'127.0.0.1',
     5               'port':3306,
     6               'user':'root',
     7               'password':'123456',
     8               'autocommit':True,
     9               'db':'db001',
    10               'charset':'utf8'}
    11 
    12 
    13 def connect():#连接数据库
    14     connect = pymysql.connect(**mysql_info)
    15     cursor = connect.cursor()
    16     return connect,cursor
    17 
    18 
    19 def execute(cursor,sql):#执行sql
    20     result = cursor.execute(sql)
    21     return result
    22 
    23 
    24 def close(connect,cursor):#关闭连接
    25     cursor.close()
    26     connect.close()
    27 
    28 
    29 connect,cursor = connect()
    30 sql = 'select * from user_info'
    31 result = execute(cursor,sql)
    32 close(connect,cursor)

    2、面向对象

     1 class MysqlDB:
     2     def __init__(self,mysql_info):
     3         self.mysql_info = mysql_info
     4         self.__connect()
     5 
     6     def __del__(self):#析构函数,实例被销毁的时候自动执行的函数
     7         self.__close()
     8 
     9     def __connect(self):#私有方法
    10         self.conn = pymysql.connect(**self.mysql_info)
    11         self.cur = self.conn.cursor(pymysql.cursors.DictCursor)
    12 
    13     def execute(self,sql):
    14         self.execute(sql)
    15 
    16     def execute_one(self):#select * from user_info where name = 'xxx';
    17         return self.cur.fetchone()
    18 
    19     def execute_all(self):#select * from user_info;
    20         return self.cur.fetchall()
    21 
    22     def execute_many(self,limit):
    23         return self.cur.fetchmany(limit)
    24 
    25     def __close(self):
    26         self.cur.close()
    27         self.conn.close()
    28 
    29 
    30 m = MysqlDB(mysql_info)
    31 m.execute('select * from user_info;')
    32 result = m.execute_all()
    33 print(result)
  • 相关阅读:
    dpi 、 dip 、分辨率、屏幕尺寸、px、density 关系以及换算
    gdb 调试
    chrome 浏览器命令
    Can't locate Switch.pm in @INC
    Git 图解剖析
    Android STL PORT
    Git 使用及原理 总结
    ndk-gdb 对java/native code联合调试(升级版)
    [转载] 关关采集不能生成html的问题
    TortoiseGit文件夹和文件图标不显示解决方法
  • 原文地址:https://www.cnblogs.com/cjxxl1213/p/13122015.html
Copyright © 2011-2022 走看看