#封装python操作mysql的类
#encoding=utf-8
import pymysql
import time
class pymysql_class():
#初始化,规定对象所拥有的属性
def init(self,host = “127.0.0.1”,user= “root”,
passwd=“root”,db=“test”,charset=“utf8”):
self.host = host
self.user = user
self.passwd = passwd
self.db = db
self.charset= charset
self.conn = pymysql.connect(host = self.host,user=self.user,
passwd = passwd,db =db,charset = charset)
self.cursor = self.conn.cursor()
#1.获取链接对象的方法
def getConn(self):
return self.conn
# 2.获取游标对象的方法
def getCursor(self):
return self.cursor
# 3.处理一个数据
def getOnedata(self,sql,param=None):
cursor =self.conn.cursor()
cursor.execute(sql,param)
#获取一个数据
one= cursor.fetchone()
cursor.close()
return one[0]
def getManydata(self,sql, param=None):
cursor = self.conn.cursor()
cursor.execute(sql,param)
# 获取多个数据
row = cursor.fetchall()
cursor.close()
return row
# 4.处理非查询的处理方法
def unquery(self,sql,args=None):
cursor =self.conn.cursor()
try:
cursor.execute(sql,args)
self.conn.commit()
except Exception as e:
print(e)
self.conn.rollback()
finally:
self.closeAll()
# 5.关闭资源的方法
def closeAll(self):
self.cursor.close()
self.conn.close()
“”"
插入语句
untils = pymysql_class()
sql = “insert into stu(id,sname,saddress) values(%s,%s,%s)”
args = (5,‘xusdb’,‘xnaud’)
untils.unquery(sql,args )
“”"
“”"
#修改语句
untils = pymysql_class()
sql = “update stu set sname = %s where id = %s "
args = (“xiaoming”,3)
untils.unquery(sql,args )
“””
#删除语句
untils = pymysql_class()
sql = “delete from stu where id = %s”
args = (3)
untils.unquery(sql,args )