1. 程式人生 > >新手學習python(十七)mysql操作

新手學習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('我是最後一行了。。。。')