1. 程式人生 > 其它 >python-mysql資料庫連線工具類封裝

python-mysql資料庫連線工具類封裝

import pymysql


class DBUtil:

    def __init__(self, database):
        self.db = pymysql.connect(host='XXXXX', port=XXXX, user='XXXX', password="XXXX",
                                  database=database)
        self.cursor = self.db.cursor()

    def query_one(self, sql):
        """查詢單條資料"""
        result 
= None try: self.cursor.execute(sql) result = self.cursor.fetchone() self.cursor.close() except Exception as e: print(e) return result def query_all(self, sql): """查詢多條資料""" list_result = () try: self.cursor.execute(sql) list_result
= self.cursor.fetchall() self.cursor.close() except Exception as e: print(e) return list_result def insert(self, sql): """新增資料""" return self.__edit(sql) def update(self, sql): """更新資料""" return self.__edit(sql) def
delete(self, sql): """刪除資料""" return self.__edit(sql) def __edit(self, sql): count = 0 try: count = self.cursor.execute(sql) self.db.commit() self.cursor.close() except Exception as e: print(e) return count if __name__ == '__main__': db = DBUtil(database='qf_marketing_usercenter_test') # sql = 'select * from org_company ' sql = 'update org_company set deleted = 0 where companyUuid = "9898bd08-8u5-4899-ab69-5300e87e3b68"' data = db.update(sql=sql) print(data)