import pymysql
class 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('我是最后一行代码了。。。')