day9_连接mysql数据库用类实现

import pymysql
class MyConnect(object):
def __init__(self, host, port, user, password, db, charset = 'utf8'):
self.host = host
self.port = port
self.user = user
self.password = password
self.db = db
self.charset = charset
self.get_cur() # 在类初始化的时候就去调用创建游标的函数
def get_cur(self):
try:
self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password,
db = self.db, charset = self.charset)
except Exception as e:
print('这里出错了,错误信息是%s' % e)
# return '数据库连接失败%s' % e
else:
self.cur = self.conn.cursor() # 建立游标
def select_sql(self, sql):
self.cur.execute(sql)
return self.cur.fetchall()
def other_sql(self, sql):
try:
self.cur.execute(sql)
except Exception as e:
print('sql执行失败%s' % e)
# return e
else:
self.conn.commit()
def __del__(self):
self.cur.close()
self.conn.close()
my = MyConnect('211.149.218.16', 3306, 'jxz', '123456', 'jxz')
res = my.select_sql('select * from jxz_stu limit 15;')
print(res)
# res1 = my.other_sql("insert into jxz_stu values('托尼帕克1','1交','1交','1交');")
# print(res1)
# res2 = my.select_sql("select * from jxz_stu where name = '托尼帕克1';")
# print(res2)
posted @ 2018-03-16 13:56  laosun0204  阅读(129)  评论(0编辑  收藏  举报