python3连接MySQL数据库

 
  1. #导入pymysql模块  
  2. import  pymysql  
  3.   
  4. class MYSQL:  
  5.     # 初始化函数,初始化连接列表  
  6.     def __init__(self,host,user,pwd,dbname):  
  7.         self.host   = host  
  8.         self.user   = user  
  9.         self.pwd    = pwd  
  10.         self.dbname = dbname  
  11.   
  12.     # 获取数据库游标对象cursor  
  13.     # 游标对象:用于执行查询和获取结果  
  14.     def getCursor(self):  
  15.   
  16.         # 建立数据库连接  
  17.         self.db = pymysql.connect(self.host,self.user,self.pwd,self.dbname)  
  18.   
  19.         # 创建游标对象  
  20.         cur = self.db.cursor()  
  21.   
  22.         # 返回  
  23.         return cur  
  24.   
  25.     # 查询操作  
  26.     def queryOperation(self,sql):  
  27.   
  28.         # 建立连接获取游标对象  
  29.         cur = self.getCursor()  
  30.   
  31.         # 执行SQL语句  
  32.         cur.execute(sql)  
  33.   
  34.         # 获取数据的行数  
  35.         row = cur.rowcount  
  36.   
  37.         # 获取查询数据  
  38.         # fetch*  
  39.         # all 所有数据,one 取结果的一行,many(size),去size行  
  40.         dataList = cur.fetchall()  
  41.   
  42.         # 关闭游标对象  
  43.         cur.close()  
  44.   
  45.         # 关闭连接  
  46.         self.db.close()  
  47.   
  48.         # 返回查询的数据  
  49.         return dataList,row  
  50.   
  51.     # 删除操作  
  52.     def deleteOperation(self,sql):  
  53.   
  54.         # 获取游标对象  
  55.         cur = self.getCursor()  
  56.         try:  
  57.             # 执行SQL语句  
  58.             cur.execute(sql)  
  59.   
  60.             # 正常结束事务  
  61.             self.db.commit()  
  62.   
  63.         except Exception as e:  
  64.             print(e)  
  65.   
  66.             # 数据库回滚  
  67.             self.db.rollback()  
  68.   
  69.         # 关闭游标对象  
  70.         cur.close()  
  71.   
  72.         # 关闭数据库连接  
  73.         self.db.close()  
  74.   
  75.     # 数据更新  
  76.     def updateOperation(self,sql):  
  77.         cur = self.getCursor()  
  78.         try:  
  79.             cur.execute(sql)  
  80.             self.db.commit()  
  81.         except Exception as e:  
  82.             print(e)  
  83.             self.db.rollback()  
  84.   
  85.         cur.close()  
  86.         self.db.close()  
  87.   
  88.     # 添加数据  
  89.     def insertOperation(self,sql):  
  90.   
  91.         cur = self.getCursor()  
  92.         try:  
  93.             cur.execute(sql)  
  94.             self.db.commit()  
  95.         except Exception as e:  
  96.             print(e)  
  97.             self.db.rollback()  
  98.   
  99.         cur.close()  
  100.         self.db.close()  
 
原文地址:https://www.cnblogs.com/meng-wei-zhi/p/8214745.html