源码:
1 import pymysql 2 3 class MysqlConnect(object): 4 # 魔术方法, 初始化, 构造函数 5 def __init__(self): 6 self.db = pymysql.connect(host=‘127.0.0.1‘, user=‘root‘, password=‘123456‘,port=3306, database=‘xueqiu‘) 7 self.cursor = self.db.cursor() 8 9 def exec(self,sql): 10 try: 11 # 执行SQL语句 12 self.cursor.execute(sql) 13 # 提交到数据库执行 14 self.db.commit() 15 except: 16 # 发生错误时回滚 17 self.db.rollback() 18 19 def select(self,sql): 20 try: 21 self.cursor.execute(sql) 22 # 获取所有记录列表 23 results = self.cursor.fetchall() 24 for row in results: 25 print(row) 26 except: 27 print("Error: unable to fetch data") 28 29 # 魔术方法, 析构化 ,析构函数 30 def __del__(self): 31 self.cursor.close() 32 self.db.close() 33 34 if __name__ == ‘__main__‘: 35 mc = MysqlConnect() 36 # mc.exec(‘insert into news(id) values(1111111)‘) 37 print(mc.select(‘select * from news;‘))
原文:https://www.cnblogs.com/zhxd-python/p/9484517.html