import pymysql class CommDB(): """封装一个万能的数据库操作类,可以执行所有的SQL语句""" def __init__(self, host, port, db, user, pwd, charset): self.host = host self.port = port self.db = db self.user =user self.pwd = pwd self.charset = charset #连接数据库 def connect(self): try: self.conn = pymysql.connect(host=self.host,port=self.port,user=self.user ,password=self.pwd,db=self.db,charset=self.charset) return True, None except Exception as e: return False,'连接数据库出错:%r'%e # 断开数据库 def disconnect(self): try: self.conn.close() return True, None except Exception as e: return False, '断开数据库出错:%r'%e def query(self,sql,bVerity=False): """封装一个传入sql语句,执行并断开操作一步到位""" co , inf = self.connect() #连接数据库 if co ==True: # 如果连接成功了 co,inf = self.execSql(sql,bVerity) co2,inf2 = self.disconnect() if co2 == False: # 如果断开失败了 print(inf2) return co,inf def execSql(self, sql,bVerity = False): #执行sql语句,bVerity是否是验证SQL try: cur = self.conn.cursor() #cursor:游标,1)可以执行任意的sql语句,2)保存返回的数据 cur.execute(sql) #用游标去执行sql语句,tuple:元组:不能修改的数组(list) data = cur.fetchall() #fetch:获取,将游标中的返回数据取出来赋给data变量 # print(len(data)) # for data1 in data: # print('***************************') # print(len(data1)) # print(data1) code = True # 有没有执行成功的标志 info = '' # 返回的附加数据信息 if bVerity == True: # 第一种:表示执行的是验证SQL info = data[0][0] #将查询出来的结果中第一行第一列数据作为返回值 elif len(data) > 0: #第二种:剩下的不是验证sql但是data中有数据,则表示是普通查询语句 info = data else: # 第三种:最后剩下的就是没有返回的 info = None cur.close() # 游标要关闭 except Exception as e: code = False # 第四种情况:执行失败了 info = e return code, info if __name__=='__main__': x = CommDB("localhost", 3306, "ranzhi", "root", "", "utf8") x.connect() #co,inf=x.execSql("select * from sys_product limit 0,1") #普通查询 #print(co,inf) co, inf = x.execSql("select count(*)=1 from sys_product where code " "= 'A200082'",True) #验证SQL print(co, inf) # co, inf = x.execSql("update sys_product set name='yang' " # "where code = 'testing1067'") #更改查询 # print(co, inf)
用python操作mysql
最新推荐文章于 2024-07-12 16:16:27 发布