最近正在研究python,用到了pymysql,但找了好久都沒有找到現成的數據庫操做類,本身封裝了一個。
類文件名字:mysql.py
代碼以下:python
import pymysqlmysql
class mysql(object):
"""[summary]
mysql數據庫操做工具類
Args:
object ([type]): [description]
"""
def init(self):
print('初始化')
self.conn = pymysql.connect('127.0.0.1','root','123456','monitor_system')
self.cursor=self.conn.cursor(cursor=pymysql.cursors.DictCursor)sql
def get_all(self,sql,args): """[summary] 返回所有符合條件的數據,args能夠有效的防止sql注入 Args: sql ([string]): [select id,name from user where id=%s and name=%s] args ([tuple]): [('123','張三'),沒有參數時傳None] Returns: [type]: [description] """ # 返回多條數據 res = '' try: print('get_all:',sql) print('args',args) self.cursor.execute(sql,args) res = self.cursor.fetchall() except Exception as e: print(e) finally: self.get_close() return res def get_one(self,sql,args): """[summary] 返回符合條件的第一條記錄,args能夠有效的防止sql注入 Args: sql ([string]): [select id,name from user where id=%s and name=%s] args ([tuple]): [('123','張三'),沒有參數時傳None] """ # 返回單條數據 res = '' try: print('get_one:',sql) print('args:',args) self.cursor.execute(sql, args) res = self.cursor.fetchone() except Exception as e: print(e) finally: self.get_close() return res def run_sql(self,sql,args): """[summary] 執行sql(無返回值), 能夠用於添加和修改操做,args能夠有效的防止sql注入 Args: sql ([string]): [insert into user (id,name) values (%s,%s)] args ([tuple]): [('123','張三'),沒有參數時傳None] """ try: print('run_sql:',sql) print('args:',args) self.cursor.execute(sql,args) self.conn.commit() except Exception as e: print(e) finally: self.get_close() def run_sql_id(self,sql,args): """[summary] 執行sql(有回值,通常爲主鍵), 能夠用於添加和修改操做,args能夠有效的防止sql注入 Args: sql ([string]): [insert into user (name,pwd) values (%s,%s)] args ([tuple]): [('123','張三'),沒有參數時傳None] Returns: [type]: [description] """ try: print('run_sql_id:',sql) print('args:',args) self.cursor.execute(sql,args) self.conn.commit() except Exception as e: print(e) finally: self.get_close() return self.cursor.lastrowid def get_date_page(self,cols,tables,orders,pageSize,pageNumber,args): """[summary] 帶翻頁帶數據 Args: cols ([string]): [須要查詢的字段,例如:id,name,pwd] tables ([string]): [須要查詢的表和搜索條件,例如:user where name=%s;若是須要用到like採用:name like concat('%','名字','%')] orders ([string]): [須要排序的字段,例如:order by name desc] pageSize ([int]): [每頁顯示多少條,例如:10] pageNumber ([int]): [當前頁(從1開始),例如3] args ([tuple]): [('123','張三'),沒有參數時傳None] Returns: [type]: [數據集合,總記錄數] """ data = '' recCount = 0 try: recBegin = (pageNumber-1)*pageSize #開始記錄 sql = f'select {cols} from {tables} {orders} limit {recBegin},{pageSize} ' print('get_date_page:',sql) print('args:',args) self.cursor.execute(sql,args) data = self.cursor.fetchall() sqlCount = f'select count(1) as count from {tables} ' self.cursor.execute(sqlCount,args) dataCount = self.cursor.fetchone() if dataCount is not None and dataCount['count']>0: recCount = dataCount['count'] except Exception as e: print(e) finally: self.get_close() page = [data,recCount] return page def get_close(self): # 釋放數據庫連接 self.cursor.close() self.conn.close()