1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| import pymysql
class MysqlDao: def __enter__(self): try: self.db = pymysql.connect( host=MYSQL_HOST, user=MYSQL_USER, password=MYSQL_PWD, database=MYSQL_DB ) self.cur = self.db.cursor() return self except Exception as e: print(e) raise e
def __exit__(self, exc_type, exc_val, exc_tb): self.cur.close() self.db.close()
def query(self, sql, args=None): try: self.cur.execute(sql, args=args) query_result = self.cur.fetchall() except Exception as e: print(e) raise e return query_result
def update(self, sql, args=None): try: effect_rows = self.cur.execute(sql, args=args) self.db.commit() except Exception as e: self.db.rollback() print(e) raise e return effect_rows
|