面向对象实例三-数据库

mac2022-06-30  104

import pymysqlclass MyDb(object):   def __del__(self): #不写也会执行(隐藏的函数,在执行最后一行代码后自动执行,用于取消内存的占用),只是利用析构函数来进行 游标、数据库连接 关闭的操作     #析构函数     self.cur.close()     self.coon.close()     print('over...')   def __init__(self,     host,user,passwd,db,     port=3306,charset='utf8'):     try:       self.coon = pymysql.connect(         host=host,user=user,passwd=passwd,port=port,charset=charset,db=db,         autocommit=True,#自动提交         )     except Exception as e:       print('数据库连接失败!%s'%e)     else:       self.cur = self.coon.cursor(cursor=pymysql.cursors.DictCursor)   def ex_sql(self,sql):     try:       self.cur.execute(sql)     except Exception as e:       print('sql语句有问题,%s'%sql)     else:       self.res = self.cur.fetchall()       return self.res

 

my = MyDb('xxx.xxx.xxx.xxx','xxx,'xxx','xxx')my.ex_sql('select * from stu;')print(my.res)print('我是最后一行代码了。。。')

转载于:https://www.cnblogs.com/lynn-chen/p/9088719.html

相关资源:php mysqli使用面向对象方式查询数据库实例
最新回复(0)