获取数据库连接: 所有方法都需要!--->可以独立出来!
init方法,负责初始连接数据库需要各种参数
、import pymysql # 导入数据库驱动模块!
class MysqlHelper():
#db = MysqlHelper('localhost',3306,'root','root','李森')
def __init__(self,host,port,user,passwd,db,charset='utf8'):
self.host= host
self.port = port
self.user = user
self.passwd = passwd
self.db = db
self.charset=charset
#self.conn = None
def connect(self):
'''功能1: 获取连接'''
self.conn = pymysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.passwd,db=self.db,charset=self.charset)
self.cursor =self.conn.cursor()
def close(self):
'''功能2:释放资源'''
self.cursor.close() #关游标
self.conn.close()# 关连接
def my_execute(self,sql,params):
'''
增删改通用功能
:param sql: sql语句
:param params: 参数列表
:return: num 影响行数
'''
num =0
# 1. 打开连接
self.connect()
num = self.cursor.execute(sql,params)
self.conn.commit()
self.close() #释放资源
return num
def get_one(self,sql,params):
'''
查询1条
:param sql: sql语句
:param params: 参数列表
:return: 1条结果
'''
result =None
#1.打开链接
self.connect()
# 2.执行查询
self.cursor.execute(sql,params)
# 3 逐行抓取
result = self.cursor.fetchone()
#4.释放资源
self.close()
return result
def get_all(self, sql, params):
'''
查询所有
:param sql: sql语句
:param params: 参数列表
:return: 1条结果
'''
result = ()
self.connect()
self.cursor.execute(sql, params)
result = self.cursor.fetchall()
self.close()
return result
if __name__ == '__main__':
# 实例化对象
db = MysqlHelper('localhost',3306,'root','root','李森')
#增加
#insert into students values(default,'张A','男',20,'山西')
'''
sql = 'insert into students values(default,%s,%s,%s,%s)'
params=['张B','男',20,'山西']
num = db.my_execute(sql,params)
print(num)
'''
# 查1条
sql = 'select * from student_1 where age =%s'
params=(12)
result =db.get_one(sql,params) #((),())
print(result)
student_1 = db.get_all(sql,params)
for stu in student_1:
print(f'名字:{stu[1]}')