【学习笔记】30、Python基础综合练习
生活随笔
收集整理的這篇文章主要介紹了
【学习笔记】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中的断言