Import Pymysql
Class MyDb (object):
def __del__ (self): #不写也会执行 (hidden function, executed automatically after the last line of code, used to cancel memory consumption), only using destructors for cursors, database connection shutdown operations
#析构函数
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 (' Database connection failed! %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 statement problematic,%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 (' I'm the last line of code ... ‘)
Object-oriented instance three-database