python-mysql操作 封裝工具類
阿新 • • 發佈:2021-09-16
import pymysql class MysqlHelper: def __init__(self, config): self.host = config["host"] self.port = config["port"] self.user = config["user"] self.password = config["password"] self.db = config["db"] self.charset = config["charset"] self.con = None self.cursor = None def create_con(self): """ 建立連線 """ try: self.con = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password, database=self.db, charset='utf8') self.cursor = self.con.cursor() return True except Exception as e: print(e) return False def close_con(self): """ 關閉連結 """ if self.cursor: self.cursor.close() if self.con: self.con.close() # sql執行 def execute_sql(self, sql): """ 執行插入/更新/刪除語句 """ try: self.create_con() print(sql) self.cursor.execute(sql) self.con.commit() except Exception as e: print(e) finally: self.close_con() def select(self, sql, *args): """ 執行查詢語句 """ try: self.create_con() print(sql) self.cursor.execute(sql, args) res = self.cursor.fetchall() return res except Exception as e: print(e) return False finally: self.close_con() if __name__ == '__main__': config = { "host": 'localhost', "port": 3306, "user": 'root', "password": '123', "db": 'test', "charset": 'utf8' } db = MysqlHelper(config) #新增 # db.execute_sql("insert into user (username, password) values ('username4','password4')") #修改 db.execute_sql("update channellist set is_active=1 where id=2") #查詢 # res = db.select("SELECT * FROM channellist;") # print(res)
從小白到大神的蛻變~~