Python | 封装调用Mysql数据库
使用pymysql模块包,对mysql数据库的增删改查进行简单封装,代码实现如下:
import pymysql class DBConnection: def __init__(self,ip='xxx',port=xxx,user='xxx',password='xxx',db='xxx'): self.ip = ip self.port = port self.user = user self.password = password self.db = db def getCon(self): try: conn = pymysql.connect(host=self.ip,port=self.port,user=self.user,passwd=self.password,database=self.db) return conn except pymysql.Error as error: print(f'mysqldb error :{error}') def select(self,sql): try: con = self.getCon() cur = con.cursor() cur.execute(sql) result = cur.fetchall() return result except pymysql.Error as error: print(f'mysqldb error :{error}') finally: cur.close() con.close() def update(self,sql): try: con = self.getCon() cur = con.cursor() cur.execute(sql) con.commit() except pymysql.Error as error: con.rollback() print(f'mysqldb error :{error}') finally: cur.close() con.close() def insert(self,sql): try: con = self.getCon() cur = con.cursor() cur.execute(sql) con.commit() except pymysql.Error as error: con.rollback() print(f'mysqldb error :{error}') finally: cur.close() con.close() def delete(self,sql): try: con = self.getCon() cur = con.cursor() cur.execute(sql) con.commit() except pymysql.Error as error: con.rollback() print(f'mysqldb error :{error}') finally: cur.close() con.close()