mysql入门第三天_pymysql操作封装

 1 import pymysql
 2 
 3 class ricosql():
 4     def __init__(self,host,user,passwd,db_name):
 5         self.host=host
 6         self.user=user
 7         self.passwd=passwd
 8         self.db_name=db_name
 9         
10     def connet(self):
11         self.db=pymysql.connect(self.host,self.user,self.passwd,self.db_name)
12         self.cursor=self.db.cursor()
13         
14     def colse(self):
15         self.cursor.close()
16         self.db.close()
17         
18     def get_one(self,sql):
19         res=None
20         try:
21             self.connet()
22             self.cursor.execute(sql)
23             res=self.cursor.fetchone()
24             self.colse()
25         except:
26             print("查询失败")
27         return res
28     
29     def get_all(self,sql):
30         res=()
31         try:
32             self.connet()
33             self.cursor.execute(sql)
34             res=self.cursor.fetchall()
35             self.colse()
36         except:
37             print("查询失败")
38             
39         return res
40     
41     def insert(self,sql):
42         return self.__edit(sql)
43     def update(self,sql):
44         return self.__edit(sql)
45     def delete(self,sql):
46         return self.__edit(sql)
47     
48     def __edit(self,sql):
49         count=0
50         try:
51             self.connet()
52             count=self.cursor.execute(sql)
53             self.db.commit()
54             self.colse()
55         except:
56             print("事物提交失败")
57             self.db.rollback()
58             
59         return count

测试:

from ricosql import ricosql

s=ricosql('localhost','root','ss@123','kaige')

res=s.get_all('select * from bandcard where money>300')
for row_res in res:
    print(row_res[0],'>>>',row_res[1])

结果:

"D:\Program Files (x86)\python36\python.exe" F:/python从入门到放弃/6.11/test.py
1 >>> 1000
4 >>> 400
5 >>> 500

Process finished with exit code 0

 

posted @ 2018-06-12 10:45  巨兽~墨菲特  阅读(113)  评论(0编辑  收藏  举报