当前位置:
首页 >
【学习笔记】30、Python基础综合练习
发布时间:2025/3/20
41
豆豆
生活随笔
收集整理的这篇文章主要介绍了
【学习笔记】30、Python基础综合练习
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
Python基础综合练习
【综合习题】
设计一个MySQL数据库操作的类,可以实现数据库的各种操作(增删改查)。
创建类源代码:
# 创建MySQL数据库操作的类 class Mysql_opeating:# 初始化方法:当对象被实例化的时候,自动创建与数据库的连接def __init__(self,host,user,password,database,charset,port = 3306):import pymysql# 用Python 连接数据库self.connect = pymysql.Connect(host = host, #"127.0.0.1",port = port, #3306,user = user, #"mao",password = password, #"123456",database = database, #"pythontest",charset = charset) #"utf8")# 创建一个光标self.cursor = self.connect.cursor()print(self.cursor)def create(self,table,*args):"""创建数据库表table:表名*args:字段及数据类型"""columns = ','.join(args)sql = "create table {} ( {} )".format(table,columns)print(sql)self.cursor.execute(sql)return '创建Table:'+table+'成功'def insert(self,table,data):"""插入数据table:表名data:多条数据(二维表格式)"""# 计算data中有几列:%s的数量n = len(data[0])# 拼接%s:列表生成式s = ','.join(["%s" for i in range(n)])self.cursor.executemany("insert into {} values({})".format(table,s),data)# 提交self.connect.commit()def select(self,col,table,condition=None):"""查询数据col:列名table:表名condition:查询条件,默认无条件"""sql = 'select {} from {}'.format(col,table)# 若condition不等于Noneif condition:sql += ' where ' + conditionprint(sql)# 执行查询语句self.cursor.execute(sql)# 提取查询结果self.data = self.cursor.fetchall() return self.datadef delete(self,table,condition=None):"""删除数据table:表名condition:查询条件,默认无条件"""sql = 'delete from ' + table if condition:sql += ' where ' + conditionprint(sql)# 执行查询语句self.cursor.execute(sql)# 提交self.connect.commit()return '删除成功'def update(self,table,key,value,condition=None):"""更新数据table:表名key:列名value:值condition:查询条件,默认无条件"""sql = "update {} set {} = '{}' where {}".format(table,key,value,condition)# 执行查询语句self.cursor.execute(sql)# 提交self.connect.commit()return '更新成功'测试:
创建实例化对象
创建数据库表
批量插入表数据
查询表数据
删除指定数据
更新指定数据
总结
以上是生活随笔为你收集整理的【学习笔记】30、Python基础综合练习的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 【学习笔记】28、类的方法及参数介绍
- 下一篇: 【学习笔记】31、Python中的断言