新手学习python(十七)mysql操作

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('118.24.3.xx','jxxx','123456','jxxxx')
my.ex_sql('select * from stu;')
print(my.res)
print('我是最后一行了。。。。')

猜你喜欢

转载自www.cnblogs.com/bainbian1234/p/9884220.html