1. 程式人生 > >封裝一個基於MySQLdb的操作類

封裝一個基於MySQLdb的操作類

'''
下載並安裝MySQLdb模組
連結地址 https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient
'''

 

 

我的環境是 python3.6 windows10 64位機器,所以下載(點選

 

下載完畢後,執行 pip install mysqlclient‑1.3.13‑cp36‑cp36m‑win_amd64.whl

 

 

下面就準備開始我們的封裝類

 

#-*- coding=utf-8 -*-
import MySQLdb
from MySQLdb import cursors
import random
class PMySQL():
    #初始化,連結資料庫並設定出字符集,並且獲取遊標
    def __init__(self):
        try:
            self.db = MySQLdb.connect('localhost','root','root','test',cursorclass=cursors.DictCursor,charset='utf8')
            
if self.db is not None: self.cursor = self.db.cursor() except Exception as e: self.cursor = '' #查詢方法 def select(self,sql): data_list = [] try: self.cursor.execute(sql) self.db.commit() data = self.cursor.fetchall()
if data is not None: for i in data: data_list.append(i) return data_list except Exception as e: return data_list #插入方法 def insert(self,sql): try: self.cursor.execute(sql) self.db.commit() return self.cursor.lastrowid except Exception as e: self.db.rollback() return 0 #更新方法 def update(self,sql): try: self.cursor.execute(sql) self.db.commit() return self.cursor.rowcount except Exception as e: self.db.rollback() return 0 #刪除方法 def delete(self,sql): try: self.cursor.execute(sql) self.db.commit() return self.cursor.rowcount() except Exception as e: self.db.rollback() return 0 if __name__ == '__main__': # 1 連結資料庫,並設定字符集 # db = MySQLdb.connect('localhost','root','root','test',cursorclass=cursors.DictCursor,charset='utf8') # print(db) # 2 獲取遊標 # cursor = db.cursor() # print(cursor) # 3 準備sql語句 # sql = 'select CONTINENT,COUNTRY,CODE from nation limit 10' # sql = 'insert into user(`name`) values("zhangsan")' # sql = "update user set name='lisi' where id=4" # sql = "delete from user where id=4" # 4 執行 # cursor.execute(sql) # 查詢 # data = cursor.fetchall() #插入 # db.commit() # print(data) # 5 處理資料 # T = [] # if data is not None: # for i in data: # T.append(i) # print(T) # print(cursor.rowcount) # 6 釋放資源,關閉連結 # db.close() p = PMySQL() sql = "delete from user where id=4" data = p.delete(sql) print(data)